// 保证没有console的浏览器不会报错
if (!window.console) {
	window.console = {
		log: function () {}
	}
}

// 全局使用的变量
var _UPLOADING_COUNT = 0; // 正在上传的计数器

/* 基本附加字符串属性 */
// 字符串左右去空字符
String.prototype.trim = function () {
	return this.replace(/(^\s*)|(\s*$)/g, '');
};
// 字符串的真实长度，汉字占两位
String.prototype.relLength = function () {
	return this.replace(/[^\x00-\xff]/ig, '  ').length;
};
/* 表单验证字符串属性 */
// 用户名，3-12位字母或数字（必须在 String.prototype.relLength() 后面）
String.prototype.isUsername = function (no_email) {
	if (no_email) {
		return /^[0-9a-zA-Z]+$/i.test(this);
	} else {
		return /^[0-9a-zA-Z]+$/i.test(this) && this.relLength() >= 3 && this.relLength() <= 12;
	}
};
// 邮箱
String.prototype.isEmail =function () {
	return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(this);
};
// 网址
String.prototype.isUrl =function () {
	return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(this);
};
// 固话
String.prototype.isPhone =function () {
	if(/^0(([0-9]{2}\-[0-9]{8}(\-[0-9]{1,})?)|([0-9]{3}\-[0-9]{7,8}(\-[0-9]{1,})?))$/.test(this)) {
		return true;
	} else if (/^[4|8]00\-[0-9]{3}\-[0-9]{4}$/.test(this)) { // 400/800电话
	
		return true;
	}
	return false;
};
// 手机
String.prototype.isMobile =function () {
	return /^(0|86)?(13[0-9]|15[012356789]|18[0236789]|14[57])[0-9]{8}$/.test(this);
};
// 密码，6-20位（必须在 String.prototype.relLength() 后面）
String.prototype.isPassword = function () {
	return this.relLength() >= 6 && this.relLength() <= 20;
};


function show_prompt (obj_str) {
	obj = $(obj_str);
	if (window.obj_str == true) {
		obj.hide();
		window.obj_str = false;
	} else {
		obj.show();
		window.obj_str = true;
	}
}

function def_img(obj, img_url) {
	if (obj.attr('src') != img_url) {
		obj.attr('src', img_url);
	}
}

function set_cookie (name, value, expire) {
	var exp = new Date();
	exp.setTime(exp.getTime() + expire);
	document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString() + ';path=/;';
}

function get_cookie (name) {
	var i, x, y, ARRcookies = document.cookie.split(";");
	for (i = 0; i < ARRcookies.length; i++) {
		x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
		y = ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x = x.replace(/^\s+|\s+$/g,"");
		if (x == name) {
			return unescape(y);
		}
	}
}

function upload_apk () {
	var obj_id = 'upload_apk';
	
	var type = $('#' + obj_id).attr('_type');
	var package_id = $('#' + obj_id).attr('_package_id');
	
	if (type == undefined) {
		type = '';
	}
	if (package_id == undefined) {
		package_id = '';
	}
	
	var upload_url;
	if (type == 'edit') { // edit
		upload_url = _URL_PATH + '/app.php?act=upload_apk&type=edit&package_id=' + package_id;
	} else if (type == 'update') { // update
		upload_url = _URL_PATH + '/app.php?act=upload_apk&type=update&package_id=' + package_id;
	} else { // add, import
		upload_url = _URL_PATH + '/app.php?act=upload_apk&type=add';
	}
	
	var file_size = '50 MB';
	
	function file_dialog_complete_handler_apk (selected, queued) {
		if (selected != 1 || queued != 1) {
			return false;
		}
		this.startUpload();
	}
	
	function file_queue_error_handler_apk (file, code, message) {
		if (code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
			alert('选择的文件超过上传最大大小限制（' + file_size + '）');
		}
	}

	function file_queued_handler_apk (file) {
		$('#upload_apk .file_name').html(file.name);
	}

	function upload_start_handler_apk (file) {
		set_uploading_count(1); // 上传计算器加一
	}

	function upload_progress_handler_apk (file, complete, total) {
		$('#upload_apk .progress').css('width', Math.ceil((complete / total) * 100) + '%');
	}

	function upload_complete_handler_apk (file) {
		set_uploading_count(-1); // 上传计数器减一
	}

	function upload_error_handler_apk (file, code, message) {
		alert("上传失败，请稍后再试！\ncode: " + code + "\nmessage: " + message);
		$('#upload_apk .file_name').html('未上传应用文件');
		$('#upload_apk .progress').css('width', '0%');
	}

	function upload_success_handler_apk (file, server_data) {
		var data = eval('(' + server_data + ')');
		if (data.success) {
			
			// 应用申诉
			if (data.error_type == 'package_exists') {
				$('#upload_apk .file_name').html('未上传应用文件');
				$('#upload_apk .progress').css('width', '0%');
				show_claim(data.package_name, false);
				return;
			}
			
			// 用户自己重复上传
			if (data.error_type == 'self_package_exists') {
				$('#upload_apk .file_name').html('未上传应用文件');
				$('#upload_apk .progress').css('width', '0%');
				show_claim(data.package_name, true, data.package_id, data.filename);
				return;
			}
			
			// min_sdk_ver太低提示
			if (!data.min_sdk_ver || parseInt(data.min_sdk_ver) < 4) {
				var msg = 'APK文件中“minSdkVersion”参数未指定或值对应的版本太低，如果继续部分市场会提交失败，确定要继续吗？\n点击“确定”继续提交，点击“取消”重新上传APK文件。';
				if (!confirm(msg)) {
					return false;
				}
			}
			
			$('#apk').val(data.apk_name);
			$('#filesize').val(data.apk_size);
			if (type != 'import') {
				// 更新应用时不回填apk文件中的应用名称到表单中
				if (type != 'update') {
					$('#label').val(data.name);
				}
				$('#versionName').val(data.ver_name);
				// icon
				$('#icon').val(data.icon_file_name);
				$('#icon_url').attr('src', data.icon_url.replace(/&amp;/g, '&'));
			}
			// screens
			$('.screen_ids').attr('checked', false);
			for (var i = 0, n = data.screens_type.length; i < n; i++) {
				$('.screen_' + data.screens_type[i]).attr('checked', 'checked');
			}
			if(type == 'update'){	
				var mydate = new Date();
				mydate.getMonth()+1; //获取当前月份(0-11,0代表1月)
				mydate.getDate(); //获取当前日(1-31)
				$('#update_desc').val((mydate.getMonth()+1)+'月'+mydate.getDate() + '日 '+data.ver_name+' 版本更新：\n')
			}
			go_s2();
			
			if (type != 'edit') {
				for (var i = 0, n = markets_ids.length; i < n; i++) {
					if ($('#priv_apk_' + markets_ids[i]).length > 0) {
						priv_apk_up(markets_ids[i], data.package_name, data.ver_code);
					}
				}
			}
			
			// check apk file on market
			if (type != 'edit') {
				if (type != 'update' && typeof(not_check_market_ids) == 'undefined') {
					not_check_market_ids = [];
				}
				//console.log(not_check_market_ids);
				setTimeout(function () {
					check_apk(data.package_name);
				}, 1000);
			}
			
			$('#icon_url').attr('_real_width', data.icon_width);
			$('#icon_url').attr('_real_height', data.icon_height);
			
		} else {
			alert(data.error);
			$('#upload_apk .file_name').html('未上传应用文件');
			$('#upload_apk .progress').css('width', '0%');
			//$('#apk').val('');
			if (type != 'edit') {
				$('#app_s2').hide();
				go_s1();
			}
			if (type == 'import') {
				$('#app_s2').show();
			}
		}
	}
	
	var settings = {
//		debug: true,
		flash_url: "js/swfupload.swf",
		upload_url: upload_url,
		file_size_limit: file_size,
		file_types: "*.apk",
		file_types_description: "Android 程序安装包",
		
		post_params: {
			'login_user_token': get_cookie('login_user_token')
		},
		
		button_image_url: _URL_PATH + "/img/btn_upload_apk.png",
		button_width: "200",
		button_height: "40",
		button_placeholder_id: "upload_apk_button",
		button_text: '',
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,
		
		file_dialog_complete_handler: file_dialog_complete_handler_apk,
		file_queue_error_handler: file_queue_error_handler_apk,
		file_queued_handler: file_queued_handler_apk,
		upload_start_handler: upload_start_handler_apk,
		upload_progress_handler: upload_progress_handler_apk,
		upload_complete_handler: upload_complete_handler_apk,
		upload_error_handler: upload_error_handler_apk,
		upload_success_handler: upload_success_handler_apk
	};
	
	new SWFUpload(settings);
}

function icon_up () {
	var file_size = '1 MB';
	
	function file_dialog_complete_handler_icon (selected, queued) {
		if (selected != 1 || queued != 1) {
			return false;
		}
		this.startUpload();
	}
	
	function file_queue_error_handler_icon (file, code, message) {
		if (code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
			alert('选择的文件超过上传最大大小限制（' + file_size + '）');
		}
	}

	function file_queued_handler_icon (file) {
		$('#icon_up .file_name').html(file.name);
	}

	function upload_start_handler_icon (file) {
		set_uploading_count(1); // 上传计算器加一
	}

	function upload_progress_handler_icon (file, complete, total) {
		$('#icon_up .progress').css('width', Math.ceil((complete / total) * 100) + '%');
	}

	function upload_complete_handler_icon (file) {
		set_uploading_count(-1); // 上传计数器减一
	}

	function upload_error_handler_icon (file, code, message) {
		alert("上传失败，请稍后再试！\ncode: " + code + "\nmessage: " + message);
		$('#icon_up .file_name').html('选择图标文件');
		$('#icon_up .progress').css('width', '0%');
	}

	function upload_success_handler_icon (file, server_data) {
//		console.log(server_data);
		var data = eval('(' + server_data + ')');
		// confirm
		if (data.message && !confirm(data.message)) {
			$('#icon_up .file_name').html('选择图标文件');
			$('#icon_up .progress').css('width', '0%');
			return false;
		}
		if (data.success) {
			$('#icon').val(data.icon_file);
			$('#icon_url').attr('src', data.icon_url.replace(/&amp;/g, '&'));
			// 回填图标真实的宽度和高度到图标的img标签上，用于验证图标的合法性
			$('#icon_url').attr('_real_width', data.icon_width);
			$('#icon_url').attr('_real_height', data.icon_height);
		} else {
			alert(data.error);
			$('#icon_up .file_name').html('选择图标文件');
			$('#icon_up .progress').css('width', '0%');
		}
	}

	var settings = {
//		debug: true,
		flash_url: "js/swfupload.swf",
		upload_url: _URL_PATH + '/app.php?act=icon_up',
		file_size_limit: file_size,
		file_types: "*.png",
		file_types_description: "PNG",
		
		post_params: {
			'login_user_token': get_cookie('login_user_token')
		},
		
		button_image_url: _URL_PATH + "/img/btn_icon_up.png",
		button_width: "146",
		button_height: "30",
		button_placeholder_id: "icon_up_button",
		button_text: '',
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,
		
		file_dialog_complete_handler: file_dialog_complete_handler_icon,
		file_queue_error_handler: file_queue_error_handler_icon,
		file_queued_handler: file_queued_handler_icon,
		upload_start_handler: upload_start_handler_icon,
		upload_progress_handler: upload_progress_handler_icon,
		upload_complete_handler: upload_complete_handler_icon,
		upload_error_handler: upload_error_handler_icon,
		upload_success_handler: upload_success_handler_icon
	};
	
	new SWFUpload(settings);
}

function screen_up (n) {
	var file_size = '10 MB';
	
	function file_dialog_complete_handler_screen (selected, queued) {
		if (selected != 1 || queued != 1) {
			return false;
		}
		this.startUpload();
	}
	
	function file_queue_error_handler_screen (file, code, message) {
		if (code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
			alert('选择的文件超过上传最大大小限制（' + file_size + '）');
		}
	}

	function file_queued_handler_screen (file) {
		$('#screen_box_' + n + ' .file_name').html(file.name);
	}

	function upload_start_handler_screen (file) {
		set_uploading_count(1); // 上传计算器加一
		delete_screen (n);
		$('#screen_close_' + n).attr('src', _URL_PATH + '/img/loading2.gif');
	}

	function upload_progress_handler_screen (file, complete, total) {
		$('#screen_box_' + n + ' .progress').css('width', Math.ceil((complete / total) * 100) + '%');
	}

	function upload_complete_handler_screen (file) {
		set_uploading_count(-1); // 上传计数器减一
		$('#screen_close_' + n).attr('src', _URL_PATH + '/img/close_2.png');
	}

	function upload_error_handler_screen (file, code, message) {
		alert("上传失败，请稍后再试！\ncode: " + code + "\nmessage: " + message);
		$('#screen_box_' + n + ' .file_name').html('选择截图文件');
		$('#screen_box_' + n + ' .progress').css('width', '0%');
	}

	function upload_success_handler_screen (file, server_data) {
		var data = eval('(' + server_data + ')');
//		console.log(data);
		if (data.success) {
			$('#screen_url_' + n).val(data.screen_file);
			$('#screen_img_' + n).attr('src', data.screen_url.replace(/&amp;/g, '&'));
		} else {
			alert(data.error);
			$('#screen_box_' + n + ' .file_name').html('选择截图文件');
			$('#screen_box_' + n + ' .progress').css('width', '0%');
		}
	}

	var settings = {
//		debug: true,
		flash_url: "js/swfupload.swf",
		upload_url: _URL_PATH + '/app.php?act=screen_up&n=' + n,
		file_size_limit: file_size,
		file_types: "*.jpg;*.png",
		file_types_description: "JPG 或 PNG",
		
		post_params: {
			'login_user_token': get_cookie('login_user_token')
		},
		
		button_image_url: _URL_PATH + "/img/btn_screen_up.gif",
		button_width: "1000",
		button_height: "1000",
		button_placeholder_id: "screen_up_" + n + "_button",
		button_text: '',
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
		
		file_dialog_complete_handler: file_dialog_complete_handler_screen,
		file_queue_error_handler: file_queue_error_handler_screen,
		file_queued_handler: file_queued_handler_screen,
		upload_start_handler: upload_start_handler_screen,
		upload_progress_handler: upload_progress_handler_screen,
		upload_complete_handler: upload_complete_handler_screen,
		upload_error_handler: upload_error_handler_screen,
		upload_success_handler: upload_success_handler_screen
	};
	
	new SWFUpload(settings);
}

function delete_screen (n) {
	$('#screen_img_' + n).attr('src', _URL_PATH + '/img/screen_up.png');
	$('#screen_url_' + n).val('');
	$('#screen_box_' + n + ' .file_name').html('选择截图文件');
	$('#screen_box_' + n + ' .progress').css('width', '0%');
}

function priv_apk_up (n, package_name, ver_code) {
	if ($('#priv_apk_button_' + n).length == 0) {
		return false;
	}
	
	var file_size = '50 MB';
	
	function file_dialog_complete_handler_priv_apk (selected, queued) {
		if (selected != 1 || queued != 1) {
			return false;
		}
		this.startUpload();
	}
	
	function file_queue_error_handler_priv_apk (file, code, message) {
		if (code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
			alert('选择的文件超过上传最大大小限制（' + file_size + '）');
		}
	}

	function file_queued_handler_priv_apk (file) {
		$('#priv_apk_' + n + ' .file_name').html(file.name);
	}

	function upload_start_handler_priv_apk (file) {
		set_uploading_count(1); // 上传计算器加一
	}

	function upload_progress_handler_priv_apk (file, complete, total) {
		$('#priv_apk_' + n + ' .progress').css('width', Math.ceil((complete / total) * 100) + '%');
	}

	function upload_complete_handler_priv_apk (file) {
		set_uploading_count(-1); // 上传计数器减一
	}

	function upload_error_handler_priv_apk (file, code, message) {
		alert("上传失败，请稍后再试！\ncode: " + code + "\nmessage: " + message);
		$('#priv_apk_' + n + ' .file_name').html('选择专属包文件');
		$('#priv_apk_' + n + ' .progress').css('width', '0%');
	}

	function upload_success_handler_priv_apk (file, server_data) {
//		console.log(server_data); return;
		var data = eval('(' + server_data + ')');
		if (data.success) {
			var sub_length = 10;
			var file_name = $('#priv_apk_' + n + ' .file_name').html();//data.priv_apk_file;
			
			$('#priv_apk_file_' + n).val(data.priv_apk_file);
			
			if (file_name.length > sub_length) {
				file_name = file_name.substr(0, sub_length - 3) + '...';
			}
			
			$('#priv_apk_' + n + ' .file_name').html(file_name);
			
			$('#priv_apk_del_' + n).show();
		} else {
			alert(data.error);
			$('#priv_apk_' + n + ' .file_name').html('选择专属包文件');
			$('#priv_apk_' + n + ' .progress').css('width', '0%');
		}
	}
	
	var settings = {
//		debug: true,
		flash_url: "js/swfupload.swf",
		upload_url: _URL_PATH + '/app.php?act=priv_apk_up',
		file_size_limit: file_size,
		file_types: "*.apk",
		file_types_description: "Android 程序安装包",
		
		post_params: {
			'login_user_token': get_cookie('login_user_token'),
			'package_name': package_name,
			'ver_code': ver_code
		},
		
		button_image_url: _URL_PATH + "/img/btn_priv_apk_up.png",
		button_width: "46",
		button_height: "30",
		button_placeholder_id: "priv_apk_button_" + n,
		button_text: '',
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,
		
		file_dialog_complete_handler: file_dialog_complete_handler_priv_apk,
		file_queue_error_handler: file_queue_error_handler_priv_apk,
		file_queued_handler: file_queued_handler_priv_apk,
		upload_start_handler: upload_start_handler_priv_apk,
		upload_progress_handler: upload_progress_handler_priv_apk,
		upload_complete_handler: upload_complete_handler_priv_apk,
		upload_error_handler: upload_error_handler_priv_apk,
		upload_success_handler: upload_success_handler_priv_apk
	};
	
	new SWFUpload(settings);
}

function delete_priv_apk (n) {
	$('#priv_apk_' + n + ' .file_name').html('选择专属包文件');
	$('#priv_apk_' + n + ' .progress').css('width', '0%');
	$('#priv_apk_file_' + n).val('');
	$('#priv_apk_del_' + n).hide();
}

function update_info () {
	if ($('#apk').val()) {
		if ( mod == 'app' && act == 'edit' ) {
			$('#upload_apk file_name').html('使用已有apk文件则不需上传');
		} else {
			$('#upload_apk file_name').html($('#apk').val());
		}
		go_s2();
	}
	
	if ($('#filesize').val()) {
		$('#apk_info_box').html($('#apk_info_box').html() + ' ' + $('#filesize').val());
	}
	if ($('#icon').val()) {
		$('#icon_url').attr('src', _URL_PATH + '/app.php?act=img&type=png&img=' + $('#icon').val());
	}
	for (var i = 1; i <= 5; i++) {
		if ($('#screen_url_' + i).val()) {
			$('#screen_img_' + i).attr('src', _URL_PATH + '/app.php?act=img' + '&type=jpg&img=' + $('#screen_url_' + i).val());
		}
	}
	var m = $('.markets[type=checkbox]');
	for (var i = 1, n = m.length; i <= n; i++) {
		var k = i - 1;
		var m_id = $(m[k]).val();
		if ($('#priv_apk_file_' + m_id).val()) {
			$('#priv_apk_list_' + m_id).html($('#priv_apk_file_' + m_id).val() + ' <a style="cursor: pointer; font-weight: normal" href="javascript:void(0)" onclick="delete_priv_apk(' + m_id + ')">删除</a>');
		}
	}
}

function check_s1 () {
	if ($('#apk').length == 0) {
		return false;
	}
	
	if (!$('#apk').val().trim()) {
		alert('请先上传apk文件！');
		location.href = '#app_s1';
		return false;
	}
	return true;
}

function check_s2 () {
	if ($('#icon_url').length > 0) { // 图标大小检查
		var w = $('#icon_url').attr('_real_width');
		if (w < ICON_WIDTH_MIN) {
			alert('图标尺寸 最小 的宽度必须是（' + ICON_WIDTH_MIN + 'px），当前宽度是（' + w + 'px），请修改后重新上传！');
			location.href = '#icon_url';
			return false;
		} else if (w > ICON_WIDTH_MAX) {
			alert('图标尺寸 最大 的宽度必须是（' + ICON_WIDTH_MAX + 'px），当前宽度是（' + w + 'px），请修改后重新上传！');
			location.href = '#icon_url';
			return false;
		}
	}
	if (act == 'update') {
		var update_desc_length = $('#update_desc').val().trim().relLength();
		if (update_desc_length < 20 || update_desc_length > 400) {
			alert('更新日志的字数请控制在20-400个字符之间！');
			return false;
		}
	}
	if (act == 'reissue') {
		return true;
	} else {
		if ($('#apk').val().trim() == '') {
			alert('请上传APK文件！');
			location.href = '#apk_up';
			return false;
		}
		
		var name_length = $('#label').val().trim().relLength();
		if (name_length < 4 || name_length > 60) {
			alert('应用名称的长度为4-30个字符！');
			$('#label').focus();
			return false;
		}
		
		if ($('#versionName').val().trim() == '') {
			alert('请填写应用版本！');
			$('#versionName').focus();
			return false;
		}
		// 版本名的限制，360市场有此限制
		if (!$('#versionName').val().trim().match(/^[a-zA-Z0-9. ]{1,20}$/)) {
			alert('版本名必须由字母、数字、小数点或空格组成，且长度不超过20个字符！');
			$('#versionName').focus();
			return false;
		}
		
		if ($('#icon').val().trim() == '') {
			alert('请上传应用图标！');
			location.href = '#icon_up';
			return false;
		}
		
		if ($('.screen_ids:checked').length == 0) {
			alert('请选择分辨率！');
			location.href = '#screen_ids';
			return false;
		}
		if ($('#cate_id').val() == 0) {
			alert('请选择分类！');
			$('#cate_id').focus();
			return false;
		}
		// 市场分类，导入应用 tool.import_app_import
		if ($('#market_cate_id').length > 0) {
			if (!$('#market_cate_id').val()) {
				alert('请选择市场分类！');
				$('#market_cate_id').focus();
				return false;
			}
		}
		
		if ($('#tag').val().trim() == '' || $('#tag').val().split(',').length > 5 || $('#tag').val().split(',').length < 2) {
			alert('关键词至少2个，并且关键词在不能超过5个，权重高的关键词请填在前面。');
			$('#tag').focus();
			return false;
		}
		if ($('#author').val().trim() == '') {
			alert('请填写作者！');
			$('#author').focus();
			return false;
		}
		if (!$('#website').val().isUrl()) {
			alert('网址未填写或格式错误（必须以“http://”开头），请检查后重新填写！');
			$('#website').focus();
			return false;
		}
		if ($('#email').val().trim() == '') {
			alert('请填写邮件！');
			$('#email').focus();
			return false;
		}
		if ($('#phone').val().trim() == '') {
			alert('请填写电话！');
			$('#phone').focus();
			return false;
		}
		var short_desc_length = $('#short_desc').val().trim().relLength();
		if (short_desc_length < 20 || short_desc_length > 40) {
			alert('简短描述的长度为20 - 40字符！汉字算2个字符');
			$('#short_desc').focus();
			return false;
		}
		var long_desc_length = $('#long_desc').val().trim().relLength();
		if (long_desc_length < 40 || long_desc_length > 2000) {
			alert('详细描述的长度为40 - 1000字符，汉字算2个字符');
			$('#long_desc').focus();
			return false;
		}
		
		var imgs_count = 0;
		for (var i = 1; i <= 5; i++) {
			if ($('#screen_url_' + i).val().trim() != '') {
				imgs_count++;
			}
		}
		if (imgs_count < 4) {
			alert('请至少上传四张应用截图！');
			$('#screen_imgs').focus();
			return false;
		}
		
		// 选择了EOE市场，但是没有上传应用授权证明
		if ($("input[name='market_id']").val() == "3" && $("#copyright_image_3").val() == "") {
			alert("优亿市场必须上传应用授权证明文件，如过要发布到该市场，必须上传“授权书复印件”！");
			$("input[name='market_id']").focus();
			$('.eoe-cy').slideDown();
			return false;
		}
		
		return true;
	}
}

function check_s3 () {
	// Notify the user when there are not finished uploading, but does not prevent the user to continue
	if (get_uploading_count() > 0) {
		if (!confirm('还有上传未完成，确认要提交吗')) {
			return false;
		}
	}
	
	if ($('.markets:checked').length == 0) {
		alert('请选择市场！');
		location.href = '#app_s2';
		return false;
	}
	for (var i = 0, n = markets_ids.length; i < n; i++) {
		if ($('.markets[name="market[' + markets_ids[i] + ']"]').attr('checked')) { // 选择了市场ID
			if (act == 'add' || act == 'update' || act == 'reissue') {
				if (!$('#market_cate_' + markets_ids[i]).val()) {
					alert('必须选择市场分类！');
					$('#market_cate_' + markets_ids[i]).addClass('error');
					$('#market_cate_' + markets_ids[i]).focus();
					return false;
				} else {
					$('#market_cate_' + markets_ids[i]).removeClass('error');
				}
			}
			
			// 如果公共账户不可用 并且未绑定个人帐号 并且选了公共账户，则提示
			var mu_obj = $('#market_username_' + markets_ids[i]);
			mu_obj.removeClass('error');
			if (!mu_obj.val() || mu_obj.val() == '@!apa') {
				alert('请选择要上传的应用的帐号');
				mu_obj.addClass('error');
				mu_obj.focus();
				return false;
			}
			
			// 选择了EOE市场，但是没有上传应用授权证明
			if ($("input[name='market[" + markets_ids[i] + "]']").val() == "3" && $("#copyright_image_" + markets_ids[i]).val() == "") {
				alert("优亿市场必须上传应用授权证明文件，如过要发布到该市场，必须上传“授权书复印件”！");
				$("input[name='market[" + markets_ids[i] + "]']").focus();
				$('.eoe-cy').slideDown();
				return false;
			}
		}
	}
	
	if ($('input[name="market[7]"]').attr('checked') && !check_text()) { // 选择了安智市场 && 检查字符的合法性
		return false;
	}
	
	// 选择了安智市场且分类是"1,53"新闻阅读，“1,55”，但是没有上传应用证明
	
	if ($('input[name="market[7]"]').attr('checked') && ($('#market_cate_7').val() == '1,53' || $('#market_cate_7').val() == '1,55')) {
		if (!$('#cy_cbl_7').val() || !$('#cy_lric_7').val() || !$('#cy_cyp_7').val()) {
			alert("安智市场必须上传应用版权验证资料！");
			$("input[name='market[7]']").focus();
			$('.anzhi_cy').slideDown();
			return false;
		}
	}
	
	return true;
}

function app_check_post (act) {
	
	if (act == 'add' || act == 'update' || act == 'edit' || act == 'import_app_import') {
		if (!check_s1()) {
			if (act != 'import_app_import') {
				go_s1();
			}
			return false;
		}
		if (!check_s2()) {
			go_s1();
			return false;
		}
	}
	if (!check_s3()) {
		go_s3();
		return false;
	}
	
	return true;
}

function go_s1 () {
	$('#app_s1').show();
	$('#app_s2').hide();
	$('#app_s3').hide();

	for (var i = 0; i < 3; i++) {
		$('#step li:eq(' + i + ')').removeClass('hist');
		$('#step li:eq(' + i + ')').removeClass('hist2');
		$('#step li:eq(' + i + ')').removeClass('cur');
	}
	$('#step li:eq(0)').addClass('cur');
	
	if ($('#apk').val().trim()) {
		$('#app_s1').show();
		$('#app_s2').show();
		
		for (var i = 0; i < 3; i++) {
			$('#step li:eq(' + i + ')').removeClass('hist');
			$('#step li:eq(' + i + ')').removeClass('hist2');
			$('#step li:eq(' + i + ')').removeClass('cur');
		}
		$('#step li:eq(0)').addClass('hist');
		$('#step li:eq(1)').addClass('cur');
	}
}

function go_s2 () {
	if (!check_s1()) {
		return false;
	}

	for (var i = 0; i < 3; i++) {
		$('#step li:eq(' + i + ')').removeClass('hist');
		$('#step li:eq(' + i + ')').removeClass('hist2');
		$('#step li:eq(' + i + ')').removeClass('cur');
	}
	$('#step li:eq(0)').addClass('hist');
	$('#step li:eq(1)').addClass('cur');
	
	$('#app_s1').show();
	$('#app_s2').show();
	$('#app_s3').hide();
	check_appname();
	fix_height();
}

function go_s3 (reload_market_cate) {
	var check_appname_result_str = $.trim($('#check_appname_result').html());
	if(check_appname_result_str){
		check_appname_result_str = check_appname_result_str.replace(/<br>/ig, "\n")
		if(confirm(check_appname_result_str+' 确定用此名字？')){
			errorMarketAppname(1);			
		}else{
			window.location.hash="label";
			return false;			
		}
	}
	
	if (!check_s2()) {
		return false;
	}
	
	// 升级页面 & 升级操作 & 分类为空，让其可选
	$('.markets').each(function () {
		var obj = $(this);
		if (obj.attr('checked')) {
			var id = obj.val();
			var obj2 = $('#market_cate_' + id);
			if (!obj2.val()) {
				obj2.attr('disabled', false);
			}
		}
		
		// 选择市场的时候检查账户是否可用
		var market_id = obj.val();
		obj.change(function () {
			check_market_user_enable(market_id);
		});
	});

	for (var i = 0; i < 3; i++) {
		$('#step li:eq(' + i + ')').removeClass('hist');
		$('#step li:eq(' + i + ')').removeClass('cur');
	}
	$('#step li:eq(0)').addClass('hist2');
	$('#step li:eq(1)').addClass('hist');
	$('#step li:eq(2)').addClass('cur');
	
	if (act == 'add' && reload_market_cate) {
		$.ajax({
			dataType: 'json',
			url: _URL_PATH + '/app.php?act=load_maket_def_cate&our_cate_id=' + $('#cate_id').val(),
			success: function (data) {
				if (data.success) {
					for (var i = 0, n = data.data.length; i < n; i++) {
						var m_id = data.data[i].market_id;
						var m_cate_id = data.data[i].market_cate_top_id + ',' + data.data[i].market_cate_id;
						$('#market_cate_' + m_id + ' option[value="' + m_cate_id +'"]').attr('selected', 'selected');
						if (m_id == 7 && (m_cate_id == '1,53' || m_cate_id == '1,55')) $('.anzhi_cy').slideDown(); // 安智市场分类更改是触发事件
					}
				}
			}
		});
	}
	
	$('#app_s1').hide();
	$('#app_s2').hide();
	$('#app_s3').show();
	
	fix_height();
	
	// 检查市场账户是否可用
	check_market_user_enable();
} 

function fix_height () {
	$('#content').css('height', 'auto');
	if ($('#header').height() + $('#content').height() + 52 < $(window).height()) {
		$('#content').css('height', $('#content').height() + $(window).height() - $('body').height());
	}
}

function confirm_app_info () {
	var scs = new Array();
	var i = 0;
	$('.screen_ids:checked').each(function () {
		scs[i] = $(this).val();
		i++;
	});
	var screens = '';
	for (k in screen_ids) {
		var dd = '';
		var has = 0;
		for (k2 in screen_ids[k]) {
			if ($.inArray(screen_ids[k][k2].id.toString(), scs) != -1) {
				dd += '<dd>' + screen_ids[k][k2].name + '</dd>';
				has++;
			}
		}
		if (has > 0) {
			screens += '<dl style="float: left; padding: 0 20px 0 0"><dt style="font-weight: bold">' + k + '</dt>' + dd + '</dl>';
		}
	}
	
	var cate_name = '';
	var cate_id = $('#cate_id').val();
	$('#cate_id option').each(function () {
		if (cate_id == $(this).val()) {
			cate_name = $(this).html();
		}
	});
	
	var img = '';
	for (var i = 1; i <= 5; i++) {
		var val = $('#screen_url_' + i).val();
		if (val) {
			img += '<div style="float: left; padding: 5px 10px 5px 0"><img width="90" style="border: solid 1px #E2E2E2; padding: 1px" src="' + _URL_PATH +'/app.php?act=img&type=jpg&img=' + val + '" /></div>';
		}
	}
	
	var market_str = '<table style="width: 100%">';
	market_str += '<tr>';
	market_str += '<th style="text-align: left">市场名</th>';
	market_str += '<th style="text-align: left">市场分类</th>';
	market_str += '<th style="text-align: left">市场账户</th>';
	market_str += '</tr>';
	$('.markets[type="checkbox"][disabled!="disabled"][checked="checked"]').parent().parent().each(function() {
		var market_id = $(this).find('td input[type="checkbox"]').val();
		var market_name = $(this).find('td a').html();
		var m_cate_id = $(this).find('td select[name|="market_cate[' + market_id + ']"]').val();
		var market_category_father = $(this).find('td select[name|="market_cate[' + market_id + ']"] option[value="' + m_cate_id + '"]').parent().attr('label'); // $("#market_cate_7 option[value='" + $("#market_cate_7").val() + "']").html();
		var market_category_son = $(this).find('td select[name|="market_cate[' + market_id + ']"] option[value="' + m_cate_id + '"]').html();
		var market_username = $(this).find('td select[name|="market_username[' + market_id + ']"]').attr('def');
		if (market_username == '') {
			market_username = '公用帐号';
		}
		
		market_str += '<tr>';
		market_str += '<td>' + market_name + '</td>';
		market_str += '<td>' + market_category_father + ' - ' + market_category_son + '</td>';
		market_str += '<td>' + market_username + '</td>';
		market_str += '</tr>';
	});
	market_str += '</table>';
	
	var msg = '<div class="ui-state-highlight ui-corner-all" style="font-size: 14px; line-height: 25px; padding: 0 10px"><table><tr><td><span class="ui-icon ui-icon-info"></span></td><td>请再次确认下列信息的准确性，一旦提交到市场，审核完成前将无法修改。</td></tr></table></div>' +
		'<table style="width: 100%; margin: 10px 0" cellpadding="5" cellspacing="0">' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">名称：</th><td style="border-bottom: solid 1px #CCC">' + $('#label').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">版本：</th><td style="border-bottom: solid 1px #CCC">' + $('#versionName').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">图标：</th><td style="border-bottom: solid 1px #CCC"><img width="48" height="48" src="' + $('#icon_url').attr('src') + '" ></td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">分辨率：</th><td style="border-bottom: solid 1px #CCC; overflow: auto">' + screens + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">类别：</th><td style="border-bottom: solid 1px #CCC">' + cate_name + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">关键词：</th><td style="border-bottom: solid 1px #CCC">' + $('#tag').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">作者：</th><td style="border-bottom: solid 1px #CCC">' + $('#author').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">网站：</th><td style="border-bottom: solid 1px #CCC">' + $('#website').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">邮箱：</th><td style="border-bottom: solid 1px #CCC">' + $('#email').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">电话：</th><td style="border-bottom: solid 1px #CCC">' + $('#phone').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">简短介绍：</th><td style="border-bottom: solid 1px #CCC">' + $('#short_desc').val() + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">应用介绍：</th><td style="border-bottom: solid 1px #CCC">' + $('#long_desc').val().replace(/\n/g, "<br />") + '</td></tr>' +
			'<tr><th style="border-bottom: solid 1px #CCC; text-align: right; white-space: nowrap">应用截图：</th><td style="border-bottom: solid 1px #CCC; overflow: auto">' + img + '</td></tr>' +
			'<tr><th style="text-align: right; white-space: nowrap">要提交的市场：</th><td>' + market_str + '</td></tr>' +
		'</table>';
	$('#dialog').html(msg);
	$('#dialog').dialog({
		title: '应用信息确认',
		width: 700,
		height: 500,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'修改': function () {
				$('#dialog').dialog('close');
				//go_s2();
			},
			'确认': function () {
				app_submit();
				$('#dialog').dialog('close');
			}
		}
	});
}

function confirm_common_market_user (act) {
	// 检测是否有公用帐号
	var has_common_market_user = false;
	$('.markets').each(function () {
		
		// 被选中的才进行操作
		if ($(this).attr('checked')) {
		
			var _market_id = $(this).val();
			
			if (!$('#market_username_' + _market_id).val()) {
				has_common_market_user = true;
			}
		}
	});

	// 有公用帐号并且未同意协议，则显示协议提示
	if (!$('#common_market_user_flg').val() && has_common_market_user) {
		var msg = '你已选择使用抓猫公用帐号提交到部分市场，<br />' +
			'需要接受<a href="' + _URL_PATH +'/static.php?act=account" target="_blank">公用帐号使用协议</a>才能继续提交';
		$('#dialog').html(msg);
		$('#dialog').dialog({
			title: '公用帐号使用协议',
			width: 500,
			modal: true,
			draggable: false,
			resizable: false,
			buttons: {
				'接受并继续': function () {
					$('#dialog').dialog('close');
					// 设置为接受协议
					$('#common_market_user_flg').val('1');
					// 提交应用
					if (act == 'add') {
						confirm_app_info(); // 添加应用时先显示应用信息确认框，确认后提交应用
					} else {
						app_submit();
					}
				},
				'返回并修改帐号': function () {
					$('#dialog').dialog('close');
				}
			}
		});
	} else {
		// 提交应用
		if (act == 'add') {
			confirm_app_info(); // 添加应用时先显示应用信息确认框，确认后提交应用
		} else {
			app_submit();
		}
	}
}

function appeal (market_id, package_id) {
	var msg = '<div style="font-size: 14px; line-height: 20px">' +
		'<form id="appeal_from" action="' + _URL_PATH +'/app.php?act=appeal" method="post" enctype="multipart/form-data">' +
			'<table style="width: 100%">' +
				'<input type="hidden" name="market_id" value="' + market_id + '">' +
				'<input type="hidden" name="package_id" value="' + package_id + '">' +
				'<tr><th style="text-align: right; white-space: nowrap"><span style="color: #F00; font-weight: normal">*</span> 姓名：</th><td><input type="text" id="appeal_name" name="name" value="' + ($('#appeal_name').length > 0 ? $('#appeal_name').val() : '') + '" style="width: 60%" /></td></tr>' +
				'<tr><th></th><td style="font-size: 12px; line-height: 18px">此姓名作为上传软件的作者名称，请如实填写，以方便我们与您取得联系，保障您的权益。</td></tr>' +
				'<tr><th style="text-align: right; white-space: nowrap"><span style="color: #F00; font-weight: normal">*</span> 邮箱：</th><td><input type="text" id="appeal_mail" name="mail" value="' + ($('#appeal_mail').length > 0 ? $('#appeal_mail').val() : '') + '" style="width: 60%" /></td></tr>' +
				'<tr><th style="text-align: right; white-space: nowrap"><span style="color: #F00; font-weight: normal">*</span> 电话：</th><td><input type="text" id="appeal_tel" name="tel" value="' + ($('#appeal_tel').length > 0 ? $('#appeal_tel').val() : '') + '" style="width: 60%" /></td></tr>' +
				'<tr><th style="text-align: right; white-space: nowrap"><span style="color: #F00; font-weight: normal">*</span> 版权说明：</th><td><textarea id="appeal_desc" name="desc" style="width: 90%; height: 100px; resize: none">' + ($('#appeal_desc').length > 0 ? $('#appeal_desc').val() : '') + '</textarea></td></tr>' +
				'<tr><th style="text-align: right; white-space: nowrap">版权证明：</th><td><input type="file" name="file" /></td></tr>' +
			'</table></form>';
		'</div>' +
	$('#dialog').html(msg);
	$('#dialog').dialog({
		title: '应用申诉',
		width: 600,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'申诉': function () {
				$('#appeal_from').submit();
				$('#dialog').dialog('close');
			}
		},
		close: function () {
			return false;
		}
	});
	return false;
}

function contact () {
	var msg = '<div style="font-size: 14px; line-height: 20px">' +
		'<form id="contact_from" action="' + _URL_PATH +'/user.php?act=contact" method="post">' +
			'<input type="hidden" name="partner" value="提交工具" />' +
			'<table style="width: 100%">' +
				'<tr><th style="text-align: right; white-space: nowrap; width: 20%; padding: 15px 0"><span style="color: #F00; font-weight: normal">*</span> 反馈类型：</th><td><select id="contact_type" name="type">' +
				'<option value="bug报告" selected="selected">bug报告</option>' +
				'<option value="功能建议">功能建议</option>' +
				'<option value="问题咨询">问题咨询</option>' +
				'<option value="建议应用市场">建议应用市场</option>' +
				'<option value="其他">其他</option>' +
				'</select>&nbsp;&nbsp;' +
				'<a target="_blank" title="通过QQ联系在线客服" href="http://b.qq.com/webc.htm?&sid=800094777">联系客服</a>' +
				'</td></tr>' +
				'<tr><th style="text-align: right; white-space: nowrap; padding; 15px 0"><span style="color: #F00; font-weight: normal">*</span> 反馈内容：</th><td><textarea id="contact_content" name="content" style="width: 90%; height: 200px; resize: none"></textarea></td></tr>' +
				'<tr><th>&nbsp;</th><td style="padding: 10px 0">如果您的反馈或问题中有图片，视频等信息，' +
					'您可以点击这里<a target="_blank" title="通过QQ联系在线客服" href="http://b.qq.com/webc.htm?&sid=800094777">联系客服</a>' +
					'也可以直接发送邮件到我们的邮箱（<a target="_blank" href="mailto:team@zhuamob.com">team@zhuamob.com</a>，邮件标题请用“用户反馈”，同时在邮件中写上您在抓猫的用户名）</td></tr>' +
			'</table></form>' +
		'</div>';
	$('#dialog').html(msg);
	$('#dialog').dialog({
		title: '意见反馈',
		width: 700,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'提交': function () {

				if ($('#contact_content').val().relLength() < 20) {
					alert('内容必须大于20个字符');
					$('#contact_content').focus();
					return false;
				}
				
				$('.ui-button').attr('disabled', 'disabled');
				$('.ui-button').parent().append('<img src="' + _URL_PATH + '/img/loading2.gif" />');

				var options = {
					dataType: 'json',
					success: function (data) {
						$('.ui-button').attr('disabled', false);
						$('.ui-button').parent().find('img').remove();
						
						if (data.success) {
							alert(data.success);
							$('#dialog').dialog('close');
						}
						if (data.error) {
							alert(data.error);
							//$('#dialog').dialog('open');
						}
					}
				};
				
				$('#contact_from').ajaxSubmit(options);
			}
		},
		close: function () {
			return false;
		}
	});
	return false;
}

function add_market () {
	var msg = '<div style="font-size: 14px; line-height: 20px">' +
		'<form id="add_market_from" action="' + _URL_PATH +'/app.php?act=add_market" method="post">' +
			'<table style="width: 100%">' +
			'<tr><th style="text-align: right; white-space: nowrap; width: 20%"><span style="color: #F00; font-weight: normal">*</span> 市场名称：</th><td><input type="text" id="add_market_name" name="name" style="width: 60%" /></td></tr>' +
			'<tr><th style="text-align: right; white-space: nowrap; width: 20%"><span style="color: #F00; font-weight: normal">*</span> 市场网址：</th><td><input type="text" id="add_market_url" name="url" style="width: 60%" /></td></tr>' +
				'<tr><th style="text-align: right; white-space: nowrap">市场说明：</th><td><textarea id="contact_content" name="desc" style="width: 90%; height: 100px; resize: none"></textarea></td></tr>' +
			'</table></form>';
		'</div>' +
	$('#dialog').html(msg);
	$('#dialog').dialog({
		title: '建议应用市场',
		width: 500,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'提交': function () {
				if (! $('#add_market_name').val().trim()) {
					alert('市场名称必须填写哦');
					$('#add_market_name').focus();
					return false;
				}
				
				if (! $('#add_market_url').val().trim()) {
					alert('市场网址必须填写哦');
					$('#add_market_url').focus();
					return false;
				}
				
				var options = {
					dataType: 'json',
					success: function (data) {
						if (data.success) {
							alert(data.success);
						}
						if (data.error) {
							alert(data.error);
							$('#dialog').dialog('open');
						}
					}
				};
				
				$('#add_market_from').ajaxSubmit(options);
				
				$('#dialog').dialog('close');
			}
		},
		close: function () {
			return false;
		}
	});
	return false;
}

function find_pos (obj) {
	var curleft = 0;
	if(obj.offsetParent)
		while(1)
		{
			curleft += obj.offsetLeft;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;

	var curtop = 0;
	if(obj.offsetParent)
		while(1)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
				break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;

	return {left: curleft, top: curtop};
}

function add_market_user_box (market_id, username, password) {
	if (! window.add_market_user_no) {
		window.add_market_user_no = 1000;
	}
	var obj = $('#market_user_' + market_id);
	var html = '<li>用户名：<input type="text" id="market_user_username_' + market_id + '_' + window.add_market_user_no + '" value="">&nbsp;&nbsp;密码：<input type="password" id="market_user_password_' + market_id + '_' + window.add_market_user_no + '" value="">&nbsp;&nbsp;<input type="button" value="绑定" onclick="do_add_market_user(' + market_id + ', ' + window.add_market_user_no + ')"></li>';
	obj.css('height', 'auto');
	obj.html(html + $('#market_user_' + market_id).html());
	$('#market_user_username_' + market_id + '_' + window.add_market_user_no).focus();
	
	window.add_market_user_no++;
}

function do_edit_market_user (market_id, num) {
	var username_obj = $('#market_user_username_' + market_id + '_' + num);
	var password_obj = $('#market_user_password_' + market_id + '_' + num);
	
	var username = username_obj.val().trim();
	var password = password_obj.val();
	
	if (check_market_user (market_id, username, password)) {
		password_obj.val('******');
		username_obj.attr('readonly', 'readonly');
	} else {
		username_obj.val('');
		password_obj.val('');
		username_obj.focus();
	}
}

function check_market_user (market_id, username, password) {
	var status = false;
	$.ajax({
		url: _URL_PATH + '/tool.php?act=edit_market_user&market_id=' + market_id + '&username=' + encodeURIComponent(username) + '&password=' + encodeURIComponent(password),
		async: false,
		dataType: 'json',
		success: function (data) {
			//console.log(data);
			alert(data.msg);
			if (data.success) {
				status = true;
			}
		}
	});
	return status;
}

function change_market_user (market_id) {
	var user_btn_obj = $('#market_user_btn_' + market_id);
	var username_obj = $('#market_username_' + market_id);
	var password_obj = $('#market_password_' + market_id);

	username_obj.attr('readonly', false);
	username_obj.val('');
	password_obj.attr('readonly', false);
	password_obj.val('');
	user_btn_obj.val('绑定');
	user_btn_obj.attr('onclick', 'do_add_market_user_2(' + market_id + ')');
	
	username_obj.focus();
}

function do_add_market_user_2 (market_id) {
	var user_btn_obj = $('#market_user_btn_' + market_id);
	var username_obj = $('#market_username_' + market_id);
	var password_obj = $('#market_password_' + market_id);

	var username = username_obj.val().trim();
	var password = password_obj.val();

	if (!username_obj.val().trim()) {
		alert('请输入要绑定的用户名');
		username_obj.focus();
		return false;
	}
	
	if (!password_obj.val()) {
		alert('请输入要绑定的密码');
		password_obj.focus();
		return false;
	}
	
	if (check_market_user (market_id, username, password)) {
		username_obj.attr('readonly', 'readonly');
		password_obj.attr('readonly', 'readonly');
		password_obj.val('******');
		user_btn_obj.val('更改');
		user_btn_obj.attr('onclick', 'change_market_user(' + market_id + ')');
	}
}

function reset_market_user (market_id, username, password) {
	var username_obj = $('#market_username_' + market_id);
	var password_obj = $('#market_password_' + market_id);
	var user_btn_obj = $('#market_user_btn_' + market_id);
	
	username_obj.val(username);
	password_obj.val(password);
	
	username_obj.attr('readonly', 'readonly');
	password_obj.attr('readonly', 'readonly');
	
	user_btn_obj.val('更改');
	user_btn_obj.attr('onclick', 'change_market_user(' + market_id + ')');
}

/**
 * Set default account
 * @param int market_id
 * @param string username
 * @param int is_default = 0 | 1
 */
function set_def_market_user (market_id, username, is_default) {
	$.ajax({
		url: _URL_PATH + '/tool.php?act=edit_market_user&market_id=' + market_id +
			'&username=' + encodeURIComponent(username) +
			'&is_default=' + is_default,
		async: false,
		dataType: 'json',
		success: function (data) {
			if (data.success) {
				$('.def_user_text[_market_id="' + market_id + '"]').hide();
				$('.def_user_text[_market_id="' + market_id + '"][_market_username="' + username + '"]').show();
			} else {
				alert(data.msg);
			}
		}
	});
}

/**
 * Add market user. Used in app.add | app.update | app.reissue
 * @param string market_id
 * @param bool select_market = false 绑定成功后是否选择该市场
 */
function add_market_user (market_id, select_market) {
	var title = '添加绑定账户';
	var body = '<ul>' +
		'<li style=" margin-bottom:10px">如果你还没有注册帐号，<a target="_blank" href="'+$('#reg_url_'+market_id).val()+'">请点击这里注册!</a></li>'+
		'<li class="cl" style="padding: 5px 0"' +
			'><label class="fl" style="width: 70px"' +
			'for="market_username">用户名：</label><input type="text" style="width: 240px" id="market_username" /></li>' +
		'<li class="cl" style="padding: 5px 0"' +
			'><label class="fl" style="width: 70px"' +
			'for="market_password">密码：</label><input type="password" style="width: 240px" id="market_password" /></li>' +
	'</ul>';
	$('#dialog').html(body);
	$('#dialog').dialog({
		title: title,
		width: 500,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'保存': function () {
				if (!$('#market_username').val()) {
					alert('请填写要绑定的用户名');
					$('#market_username').addClass('error');
					$('#market_username').focus();
					return false;
				}
				if (!$('#market_password').val()) {
					alert('请填写绑定用户的密码');
					$('#market_password').focus();
					$('#market_password').addClass('error');
					return false;
				}
				
				$.ajax({
					url: _URL_PATH + '/tool.php?act=edit_market_user&market_id=' + market_id +
						'&username=' + encodeURIComponent($('#market_username').val()) +
						'&password=' + encodeURIComponent($('#market_password').val()),
					async: false,
					dataType: 'json',
					success: function (data) {
						alert(data.msg);
						if (data.success) {
							$('<option value="' + $('#market_username').val().trim() + '">' +
								$('#market_username').val().trim() + '</option>').insertBefore('.add_market_user_' + market_id);
							$('#market_username_' + market_id).val($('#market_username').val().trim());
							$('#market_username_' + market_id).attr('def', $('#market_username').val().trim());
							
							// 选定市场，标记已经有绑定用户了
							if (select_market) {
								$('input[name="market[' + market_id + ']"]').attr('_red_bg', '');
								$('#market_username_' + market_id).attr('has_user_account', '1');
								change_market_li_status(market_id, 1, '', '', 1);
								$('.eoe-cy').slideDown();
							}
							
							$('#dialog').dialog('close');
						}
					}
				});
			}
		}
	});
}

var refresh_market_user_close_mark = true;
var refresh_market_user_success_mark = false;
function refresh_market_user (market_id, username, market_name) {
	refresh_market_user_close_mark = false;
	refresh_market_user_success_mark = false;
	show_box('#refresh_market_user_box', function () {
		refresh_market_user_close_mark = true;
		if (refresh_market_user_success_mark) {
			location.reload();
		}
	});
	$('#rf_m_u').html($('#rf_m_u').html().replace(/#market#/, market_name).replace(/#username#/, username));
	$.ajax({
		url: '/tool.php?act=refresh_market_user&market_id=' + market_id + '&username=' + username,
		dataType: 'json',
		success: function (data) {
			if (refresh_market_user_close_mark) { // 刷新窗口已经关闭了，结果不显示
				return false;
			}
			// 返回信息显示
			$('#rf_m_u').html(data.msg);
			if (data.success) {
				$('#rf_m_u').css('color', '#000');
				$('#rf_m_u').css('font-weight', 'normal');
				refresh_market_user_success_mark = true;
			} else {
				$('#rf_m_u').css('color', '#f00');
				$('#rf_m_u').css('font-weight', 'bold');
			}
			setTimeout(function () {
				hide_box();
				location.reload();
			}, 2000);
		},
		complete: function (xhr, ts) {
			if (xhr.status != 200 || ts == 'parsererror') {
				hide_box();
				alert('请求出错，可能是网络问题。请稍后再试！');
			}
		}
	});
}

/**
 * Edit market user. Used in user.market_user<br>
 * edit_market_user(1) // add market user<br>
 * edit_market_user(1, 'joe') // change market user password<br>
 * @param int market_id
 * @param string username = undefined (add market user) | exists_market_user_username (change market user password)
 */
function edit_market_user (market_id, username) {
	var title = '';
	var username_disabled = false;
	if (username == undefined) { // add market user
		title = '添加绑定账户';
		username = '';
		username_disabled = false;
	} else { // edit market user password
		title = '更改绑定账户密码';
		username_disabled = true;
	}
	var warning = '';
	if (parseInt(market_id) == 18) {
		warning = '应网易应用中心要求，抓猫建议企业级开发者移步网易应用中心后台提交应用。网易应用中心有专人负责接待，可以快速上线。';
	}
	if (warning) {
		warning = '<li style="border-top: solid 1px #ccc; margin-top: 10px; padding-top: 5px; color: #f00">提示：' + warning + '</li>';
	}
	
	var body = '<ul>' +
			'<li style=" margin-bottom:10px">如果你还没有注册帐号，<a target="_blank" href="' + $('.market_link_' + market_id).attr('href') + '">请点击这里注册!</a></li>'+
			'<li class="cl" style="padding: 5px 0"' +
				'><label class="fl" style="width: 70px"' +
				'for="market_username">用户名：</label><input type="text" style="width: 240px" id="market_username" value="' + username + '"' +
				(username_disabled ? ' readonly="readonly" class="readonly"' : '') + ' /></li>' +
			'<li class="cl" style="padding: 5px 0"' +
				'><label class="fl" style="width: 70px"' +
				'for="market_password">密码：</label><input type="password" style="width: 240px" id="market_password" /></li>' +
			'<li style="border-top: solid 1px #ddd; padding-top: 10px; margin-top: 10px">提示信息：<strong id="be_mu_rs" class="red">&nbsp;</strong></li>' +
			warning +
		'</ul>';
	$('#dialog').html(body);
	$('#dialog').dialog({
		title: title,
		width: 500,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'保存': function () {
				if (!$('#market_username').val()) {
					alert('请填写要绑定的用户名');
					$('#market_username').addClass('error');
					$('#market_username').focus();
					return false;
				}
				if (!$('#market_password').val()) {
					alert('请填写绑定用户的密码');
					$('#market_password').focus();
					$('#market_password').addClass('error');
					return false;
				}
				show_loading(true, '正在验证账号，请稍等……');
				$('#dialog').dialog('close', true);
				
				$.ajax({
					url: _URL_PATH + '/tool.php?act=edit_market_user&market_id=' + market_id +
						'&username=' + encodeURIComponent($('#market_username').val()) +
						'&password=' + encodeURIComponent($('#market_password').val()),
					async: true, // 必须打开异步，不然loading box是不会显示的
					dataType: 'json',
					success: function (data) {
						show_loading(false);
						if (data.success) {
							if(confirm(data.msg + "\n如果帐号里面已经发布过应用可以使用使用：\n【工具-应用接管】功能接管已经存在的应用\n现在就去接管应用吗")) {
								window.location.href = _URL_PATH + '/tool.php?act=import_app_guide&market_id=' + market_id + '&market_username=' + $('#market_username').val();
								return true; // 终止
							}
							$('#dialog').dialog('close');
							location.reload();
						} else {
							$('#dialog').dialog('open', true);
							$('#be_mu_rs').html(data.msg);
						}
					}
				});
			}
		}
	});
}

function ck_fun(market_id,package_name,file_name){
//	change_market_li_status(market_id, 0, '正在检查 <strong>' + package_name + '</strong> 是否已存在  ...', 'none', false);
	change_market_li_status(market_id, 0, '正在检查应用是否已存在  ...', 'none', false);
		
		$.ajax({
			url: _URL_PATH + '/app.php?act=check_apk&market_id=' + market_id + '&file_name=' + encodeURIComponent(file_name),
			dataType: 'json',
			success: function (data) {
				//console.log(data.market_id, data);
				if (data.status == 1) {
					var msg;
					if (act == 'update') {
						msg = '市场已存在该应用，无法更新';
					} else {	
						msg = '市场已存在该应用，无法进行操作';
					}
					$('#app_ignore_'+market_id).show();
					$('#app_recheck_'+market_id).show();	
					// apk 冲突的 背景灰掉
					change_market_li_status(data.market_id, -1, msg, '#EEE', false);
				} else {
					// 如果公共账户不可用并且未绑定该市场的个人账户，市场的复选框默认不被选中
					var checked = false;
					if (!$('input[name="market\[' + data.market_id + '\]"]').attr('_red_bg')) {
						checked = 'checked';
					}
					$('#app_ignore_'+market_id).hide();
					$('#app_recheck_'+market_id).show();
					change_market_li_status(data.market_id, 1, '', 'none', checked);
				}
			}
		});
}
function ignore (market_id, market_name) {
	var c=confirm('确定要忽略' + market_name + '报告的应用冲突吗？');
	if (c==true) {
		if ($('input[name="market\[' + market_id + '\]"]').attr('_status')) {
			var para = $('input[name="market\[' + market_id + '\]"]').attr('_status').split('|');
			change_market_li_status(market_id, para[0], para[1], para[2], para[3] == 'false' ? false : true);
			
 		} else {
			var checked = false;
			if (!$('input[name="market\[' + market_id + '\]"]').attr('_red_bg')) {
				checked = 'checked';
			}
			change_market_li_status(market_id, 1, '', '#fff', checked);
		}
		$('#app_ignore_'+market_id).hide();
		$('#app_recheck_'+market_id).show();
	} else {
		return false;
	}
}

function ck_apk(market_id)
{
	var package_name=$('#apk_file_name').html();
	var file_name = $('#apk').val();
	ck_fun(market_id,package_name,file_name);
}
function check_apk (package_name) {
	var file_name = $('#apk').val();

	// 获取不可更新的 市场 的 id
	var not_update_market_ids = [];
	for (var i = 0, n = market_can_not_update_json.length; i < n; i++) {
		not_update_market_ids.push(parseInt(market_can_not_update_json[i].id));
	}
	
	for (var i = 0, n = markets_ids.length; i < n; i++) {
		var market_id = markets_ids[i];
		
		// 被关闭的市场不检查apk
		if ($.inArray(market_id, _CLOSED_MARKET_IDS) > -1) {
			continue;
		}
		// 不检查apk的市场不检查apk
		if ($.inArray(market_id, _NOT_CHECK_APK_MARKET_IDS) > -1) {
			continue;
		}
		// 不可更新的不检查apk
		if ($.inArray(market_id, not_update_market_ids) > -1) {
			continue;
		}
		ck_fun(market_id,package_name,file_name);
		
	}
}


/* report */
function change_chart (m_id) {

	if (m_id == 0) {
		$('#chart_markets_id input:checkbox').attr('checked', false);
		$('#chart_markets_id input:checkbox[value="0"]').attr('checked', 'checked');
	} else {
		$('#chart_markets_id input:checkbox[value="0"]').attr('checked', false);
	}
	
	var series = new Array();

	$('#chart_markets_id input:checkbox').each(function () {
		if ($(this).attr('checked')) {
			var m_id = $(this).val();
			series [series.length] = chart_json.series [m_id];
		}
	});
	
	create_chart(chart_json.categories, series);
}

function create_chart (categories, series) {
	new Highcharts.Chart({
		chart: {
			renderTo: 'report_chart',
			defaultSeriesType: 'line',
			marginRight: 100,
			marginBottom: 80
		},
		title: {
			text: '',
			x: -20 //center
		},
		subtitle: {
			text: '',
			x: -20
		},
		xAxis: {
			labels:{
				align:'right',
				rotation:-70
			},
			categories: categories
		},
		yAxis: {
			min: 0,
			title: {
				text: '下载量'
			},
			plotLines: [{
				value: 0,
				width: 1,
				color: '#808080'
			}]
		},
		tooltip: {
			formatter: function() {
				return '<b>'+ this.series.name +'</b><br/>'+
				this.x +': '+ this.y +' 次';
			}
		},
		legend: {
			layout: 'vertical',
			align: 'right',
			verticalAlign: 'top',
			x: -10,
			y: 100,
			borderWidth: 0
		},
		series: series
	});
	$('tspan:contains("Highcharts.com")').remove();
}

// check reg s3 form
function check_reg_s3 () {
	var user_obj = $('#user');
	var user = user_obj.val().trim();
	
	if (!user.isUsername()) {
		alert('用户名，3-12位字母或数字');
		user_obj.addClass('error');
		user_obj.focus();
		return false;
	}

	var pass_obj = $('#pass');
	var pass2_obj = $('#pass2');
	var pass = pass_obj.val();
	var pass2 = pass2_obj.val();

	if (pass.length < 6 || pass.length > 20) {
		alert('密码的长度必须是6-20位');
		pass_obj.addClass('error');
		pass_obj.focus();
		return false;
	}

	if (pass != pass2) {
		alert('两次输入的密码不一致');
		pass2_obj.addClass('error');
		pass2_obj.focus();
		return false;
	}
	
	return true;
}

function check_change_pass () {
	if ($('#pass').length > 0) {
		var pass_obj = $('#pass');
		var pass = pass_obj.val();
	
		if (pass.length < 6 || pass.length > 20) {
			alert('原密码的长度必须是6-20位');
			pass_obj.addClass('error');
			pass_obj.focus();
			return false;
		}
	}
	
	var new_pass_obj = $('#new_pass');
	var new_pass2_obj = $('#new_pass2');
	var new_pass = new_pass_obj.val();
	var new_pass2 = new_pass2_obj.val();

	if (new_pass.length < 6 || new_pass.length > 20) {
		alert('密码的长度必须是6-20位');
		new_pass_obj.addClass('error');
		new_pass_obj.focus();
		return false;
	}

	if (new_pass != new_pass2) {
		alert('两次输入的密码不一致');
		new_pass2_obj.addClass('error');
		new_pass2_obj.focus();
		return false;
	}
	
	return true;
}

var reg_s3_username_notice = null;
function check_username (username) {
	if (!reg_s3_username_notice) {
		reg_s3_username_notice = $('#reg_s3_username_notice').html();
	}
	if (username == '') {
		$('#reg_s3_username_notice').css('color', '#F00');
		$('#reg_s3_username_notice').html('请填写用户名');
		$('#user').addClass('error');
		setTimeout(function () {
			$('#user').focus();
		}, 100); // need a little delay in the focusing when use "onblur" on the same element
		return false;
	}
	
	if (!username.match(/^[a-zA-Z0-9]+$/)) {
		$('#reg_s3_username_notice').css('color', '#F00');
		$('#reg_s3_username_notice').html('用户名只能是字母或数字');
		$('#user').addClass('error');
		setTimeout(function () {
			$('#user').focus();
		}, 100); // need a little delay in the focusing when use "onblur" on the same element
		return false;
	}
	
	$.ajax({
		dataType: 'json',
		url: _URL_PATH + '/user.php?act=check_user&username=' + encodeURIComponent(username),
		success: function (data) {
			if (data.error) {
				$('#user').addClass('error');
				$('#reg_s3_username_notice').css('color', '#F00');
				$('#reg_s3_username_notice').html(data.error);
				$('#user').focus();
			} else {
				$('#user').removeClass('error');
				$('#reg_s3_username_notice').css('color', '#666');
				$('#reg_s3_username_notice').html(reg_s3_username_notice);
			}
		}
	});
}

function update_comfirm_box (data) {
	if (data.length == 0) {
		return false;
	}
	var body = '<div style="line-height: 25px">';
	if (NOT_SUPPORT_UPDATE_MARKET) {
		var m_name = new Array();
		for (i in NOT_SUPPORT_UPDATE_MARKET) {
			m_name[i] = NOT_SUPPORT_UPDATE_MARKET[i].name;
		}
		body += '<strong class="red">注意：' + m_name.join('、') + '更新功能暂不支持</strong><br />';
	}
	body += '审核中应用无法被更新。此应用在以下 '+ data.length +' 个市场中：<br />';
	for (var i = 0, n = data.length; i < n; i++) {
		body += '&nbsp;&nbsp;&nbsp;&nbsp;' + data[i].name + ' ' + data[i].status + '<br />';
	}
	body += '将无法更新，是否继续？<br />' +
		'<a href="/help.php?act=faq#id_15" target="_blank">了解更多...</a>';
	$('#dialog').html(body);
	$('#dialog').dialog({
		title: '更新提示',
		width: 500,
		modal: true,
		draggable: false,
		resizable: false,
		buttons: {
			'继续': function () {
				$('#dialog').dialog('close');
			},
			'取消': function () {
				history.go(-1);
			}
		}
	});
}

function app_submit (app_act) {
	var options = {
		dataType: 'json',
		success: function (data) {
			$('#app_submit').attr('disabled', false);
			
			if (data.success) {
				
				//alert(data.go);
				
				location.href = data.go;
				
			} else {
				
				show_loading(false);
				
				alert(data.error);
				
				if (data.go == 's1') {
					go_s1();
				}
				if (data.go == 's2') {
					go_s2();
				}
				if (data.go == 's3') {
					go_s3();
				}
				
			}
		}
	};
	
	show_loading(true, '正在提交，请稍等……');
	$('#app_add').ajaxSubmit(options);
}

/**
 * 更改市场列表项状态
 * @param market_id
 * @param status 复选框状态。 -1: error; 0: loading; 1: ok
 * @param text：遮罩提示文字
 * @param bg_color 背景颜色
 * @param checked 是否被选中
 * @param remember_status 记住状态
 */
function change_market_li_status (market_id, status, text, bg_color, checked, remember_status) {
	// status: -1: error; 0: loading; 1: ok;
	// bg_color: 背景无颜色时用 ''，不能用 'none'
	//console.log(market_id, status, text, bg_color, checked);
	
	// 用 市场 复选框 记录 市场列表状态
	if (remember_status) {
		var obj = $('input[name="market\[' + market_id + '\]"]');
		obj.attr('_status', status + '|' + text + '|' + bg_color + '|' + checked);
	}
	
	// 状态图标，状态提示文字，显示私有apk上传界面，是否显示状态 div, id复选框是否可用
	if (status == -1) {
		$('#market_loading_box_' + market_id).css('background-image', 'url(' + _URL_PATH + '/img/stop.png)');
		$('#market_loading_box_' + market_id).html(text);
		$('#priv_apk_' + market_id).hide();
		$('#market_loading_box_' + market_id).parent().show();
		$('input[name="market\[' + market_id + '\]"]').attr('disabled', 'disabled');
	} else if (status == 0) {
		$('#market_loading_box_' + market_id).css('background-image', 'url(' + _URL_PATH + '/img/loading2.gif)');
		$('#market_loading_box_' + market_id).html(text);
		$('#priv_apk_' + market_id).hide();
		$('#market_loading_box_' + market_id).parent().show();
		$('input[name="market\[' + market_id + '\]"]').attr('disabled', 'disabled');
	} else if (status == 1) {
		$('#market_loading_box_' + market_id).css('background-image', 'none');
		$('#market_loading_box_' + market_id).html('');
		$('#priv_apk_' + market_id).show();
		$('#market_loading_box_' + market_id).parent().hide();
		$('input[name="market\[' + market_id + '\]"]').attr('disabled', false);
	}
	
	// 市场列表背景颜色
	$('#market_loading_box_' + market_id).parent().css('background-color', bg_color);
	$('#market_loading_box_' + market_id).parent().parent().css('background-color', bg_color);
	
	// 复选框是否被选中
	if (checked) {
		$('input[name="market\[' + market_id + '\]"]').attr('checked', 'checked');
	} else {
		$('input[name="market\[' + market_id + '\]"]').attr('checked', false);
	}
}

// 正在上传计数器
function set_uploading_count (add_number) {
	if (add_number < 0 && _UPLOADING_COUNT <= 0) {
		return false;
	}
	_UPLOADING_COUNT = _UPLOADING_COUNT + add_number;
	//console.log(_UPLOADING_COUNT);
	return _UPLOADING_COUNT;
}
function get_uploading_count () {
	return _UPLOADING_COUNT;
}

function download_partner_apk () {
	var apk_url = $('#apk_url').val();
	$('#upload_apk .file_name').html('<img src="/img/loading2.gif" /> <span style="color: red">正在下载应用文件，请稍候...</span>');
	$.ajax({
		dataType: 'json',
		url: _URL_PATH + '/app.php?act=download_partner_apk&apk_url=' + encodeURIComponent(apk_url) + '&r=' + encodeURIComponent(new Date()),
		success: function (rs) {
			if (rs.status) {
				$('#apk').val(rs.data.file_name);
				$('#upload_apk .file_name').html(rs.data.file_name);
				$('#filesize').val(rs.data.size);
				
				$('#icon').val(rs.data.icon);
				$('#icon_url').attr('src', _URL_PATH + '/app.php?act=img&type=png&img=' + rs.data.icon);
				
				$('#versionName').val(rs.data.ver_name);
				
				$('#label').val(rs.data.name);
				
				$('.screen_ids').attr('checked', false);
				for (var i = 0, n = rs.data.screen_types.length; i < n; i++) {
					$('.screen_' + rs.data.screen_types[i]).attr('checked', 'checked');
				}
				
				// 上传专属apk
				for (var i = 0, n = markets_ids.length; i < n; i++) {
					priv_apk_up (markets_ids[i], rs.data.package_name, rs.data.ver_code);
				}
				
				go_s2();
			} else {
				if (!rs.data.retry) {
					$('.re_dl_ptr_apk').hide();
				}
				$('#upload_apk .file_name').html('<span style="color: red">下载apk文件失败 [ ' + rs.msg + ' ]</span>');
				if (rs.data.status == 'UPLOADED_BY_OTHER') { // 被其他人上传，应用申诉
					show_claim(rs.data.package_name, false);
				} else if (rs.data.status == 'UPLOADED_BY_SELF') { // 跳到应用详情页
					show_claim(rs.data.package_name, true, rs.data.package_id, rs.data.filename);
				} else {
					alert('下载apk文件失败 [ ' + rs.msg + ' ]' + (rs.data.retry ? '，可以点击“重新下载”按钮重试' : ''));
				}
			}
		}
	});
}

function show_box (obj_name, close_event) {
	
	if (!close_event) {
		close_event = function () {};
	}
	
	var obj = $(obj_name);
	var html = obj.html();
	obj.html('');
	
	var title = obj.attr('title') ? obj.attr('title') : "抓猫提示";
	var w = obj.attr('width') ? obj.attr('width') : (parseInt(obj.css('width')) ? parseInt(obj.css('width')) : 500);
	var h = obj.attr('height') ? obj.attr('height') : (parseInt(obj.css('height')) ? parseInt(obj.css('height')) : "auto");
//	console.log(w, h);
	
	$('#dialog').html(html);
	$('#dialog').dialog({
		title: title,
		width: w,
		height: h,
		modal: true,
		draggable: false,
		resizable: false,
		beforeClose: function (event, ui) {
			obj.html(html);
		},
		close: close_event
	});
}
function hide_box () {
	$('#dialog').dialog('close');
}

function delete_app (package_id) {
	return delete_app_common('app', null, package_id);
}

function delete_app_on_market (market_id, package_id) {
	return delete_app_common('app_on_market', market_id, package_id);
}

function delete_app_common (del_type, market_id, package_id) {
	show_box('#delete_app_confirm_box');
	load_verify_img(); // 加载验证码
	$('#delete_app_confirm_form').submit(function () {
		var verify_code = $('#verify_code').val();
		verify_code = verify_code ? verify_code : '';
		if ($('#verify_code').length > 0 && verify_code.length != 4) {
			alert('验证码错误！');
			$('#verify_code').focus();
			return false;
		}
		
		if (del_type == 'app') {
			var url = _URL_PATH + '/app.php?act=delete_app&package_id=' + package_id + '&code=' + verify_code;
		} else if (del_type == 'app_on_market') {
			var url = _URL_PATH + '/app.php?act=delete_app_on_market&market_id=' + market_id + '&package_id=' + package_id + '&code=' + verify_code;
		}
		
		show_loading(true, '正在执行删除操作...');
		
		$.getJSON(url, function (data) {
			show_loading(false);
			if (data.status == 0) {
				hide_box();
				alert(data.message);
				location.reload();
			} else {
				alert(data.message + '[' + data.status + ']');
				refresh_verify_img();
				if(data.status == -5 || data.status == -6) {
					$('#verify_code').val('');
					$('#verify_code').focus();
				}
			}
		});
		
		return false;
	});
}

function market_user_delete (market_id, market_username) {
	if (confirm('您确定要解除此市场账号额绑定吗？')) {
		location.href = _URL_PATH + '/tool.php?act=market_user_delete&market_id=' + market_id + '&market_username=' + encodeURIComponent(market_username);
	}
}

function select_add_market_user (obj_name, market_id) {
	var obj = $(obj_name);
	var val = obj.val();
	var def = obj.attr('_def');
	if (val == '@_sys_add') {
		add_market_user(market_id);
		obj.val(def);
		return false;
	} else {
		obj.attr('_def', val);
	}
}

//检查每个市场 是否检查appname
function check_appname(){
	var appname = $.trim($('#label').val());
	if(!appname){return false;}
	// 获取不可更新的 市场 的 id
	var not_update_market_ids = [];
	for (var i = 0, n = market_can_not_update_json.length; i < n; i++) {
		not_update_market_ids.push(parseInt(market_can_not_update_json[i].id));
	}
	//标识那些重复的市场id
	errorMarketAppname(0);
	$('#check_appname_result').html('');
	$('#repeat_market_id').html('');
	for (var i = 0, n = markets_ids.length; i < n; i++) {
		var market_id = markets_ids[i];
		
		// 被关闭的市场不检查apk
		if ($.inArray(market_id, _CLOSED_MARKET_IDS) > -1) {
			continue;
		}
		check_appname_fun(market_id,appname);		
	}
}
//检查appname
function check_appname_fun(market_id,appname){	
	$.ajax({
		url: _URL_PATH + '/app.php?act=check_appname&market_id=' + market_id + '&appname=' + encodeURIComponent(appname),
		dataType: 'json',
		success: function (data) {
			if (data.status == 1) {
				//重复市场id用,链接
				$('#repeat_market_id').append(data.market_id+",");
				var msg = data.msg;
				$('#check_appname_result').append(msg+" 建议更换,否则此市场不能提交<br />");
				var reg = /无法/;
				var erro_tmp = $('#market_loading_box_'+market_id).html();
				if(!reg.test(erro_tmp) && act == 'add') {
					change_market_li_status(market_id, -1, '应用名称不符合要求', '#EEE', false, true);
					$('#app_recheck_' + market_id).hide();
					$('#app_ignore_' + market_id).hide();					
				}			
			}
		}
	});
	
}
//标识那些重复的市场id 显示还是不显示
function errorMarketAppname(show){
	if(act != 'add') {return false;}
	//标识那些重复的市场id
	var repeat_market_id = $('#repeat_market_id').html();
	if(repeat_market_id) {
		var repeat_market_arr =  repeat_market_id.split(",");
		for(var i=0, n=repeat_market_arr.length; i < n; i++){
			var t_market_id = repeat_market_arr[i];			
			if(t_market_id){
				var reg = /无法/;
				var erro_tmp = $('#market_loading_box_'+t_market_id).html();
				if(!reg.test(erro_tmp)) {
					if(show == 0){
						change_market_li_status(t_market_id, 1, '', '#FFFFAA', false, true);
						$('#app_recheck_' + t_market_id).show();
						$('#app_ignore_' + t_market_id).show();							
					} else {
						change_market_li_status(t_market_id, -1, '应用名称不符合要求', '#EEE', false, true);
						$('#app_recheck_' + t_market_id).hide();
						$('#app_ignore_' + t_market_id).hide();							
					}				
				}				
			}
		}		
	}	
}

// 检查字符合法性（目前只支持安智市场）
function check_text () {
	return true;
	var success_flg = false;
	$.ajax({
		url: '/app.php?act=check_text&market_id=7',
		type: 'POST',
		data: {
			author: $('#author').val(),
			name: $('#label').val(),
			long_desc: $('#long_desc').val(),
			tag: $('#tag').val(),
			update_desc: $('#update_desc').val()
		},
		dataType: 'json',
		async: false,
		success: function (data) {
			if (data.status != 1) { // 检查失败
				var msg = '【安智市场】 ' + data.msg;
				$('#check_appname_result').append(msg + '<br />');
				if (confirm(msg + "\n确定要继续吗？\n点击“确定”继续操作，点击“取消”修改信息。")) {
					success_flg = true;
				}
			} else {
				success_flg = true;
			}
		}
	});
	return success_flg;
}

function select_all (self, target, not_select) {
	var checked = false;
	if ($(self).attr('checked')) {
		checked = 'checked';
	}
	
	$(target).each(function () {
		if (!($.inArray($(this).val(), not_select) > -1)) {
			$(this).attr('checked', checked);
		}
	});
}

function change_chart_all (self, target, not_select) {
	select_all (self, target, not_select);
	
	if ($(self).attr('checked')) {
		$(target + '[value="0"]').attr('checked', false);
		
		$(target).each(function () {
			var val = $(this).val();
			if (!($.inArray(val, not_select) > -1)) {
				change_chart(val);
			}
		});
	} else {
		$(target + '[value="0"]').attr('checked', 'checked');
		change_chart(0);
	}
}

// 应用在抓猫中冲突申诉
function show_claim (package_name, self_package, package_id, filename) {
	$('#dialog').css('padding', '0'); // 重置对话框的填充值
	
	$('#claim_box').html($('#claim_box').html().replace(/#package_name#/g, package_name)); // 替换提示中的包名
	if (package_id) {
		$('#claim_box').html($('#claim_box').html().replace(/#package_id#/g, package_id));
	}
	if (filename) {
		$('#claim_box').html($('#claim_box').html().replace(/#filename#/g, filename));
	}
	
	if (self_package) {
		$('#claim_box').attr('title', '应用已存在');
		$('#claim_box').attr('width', '500');
		$('#claim_box').attr('height', '200');
		
		$('.self_claim_message').show();
		$('.claim_message').hide();
		show_box('#claim_box');
		return;
	} else {
		$('.self_claim_message').hide();
		$('.claim_message').show();
	}
	
	// 显示提示框
	show_box('#claim_box');
	
	$('.go_claim').click(function () {
		hide_box(); // 隐藏申诉对话框
		show_box('#claim_info_box'); // 显示申诉信息框
		
		$('#claim-info-p-name').val(package_name); // 写入 package_name
		
		$('#cib-add').click(function () { // 添加市场帐号信息项目
			$('#cib-add-before').before('<tr class="cib-item">' + $('#cib-item-tpl').html() + '</tr>');
		});
		
		$('#claim-submit').click(function () { // 提交后关闭申诉信息框
			if (!check_claim()) {
				return false;
			}
			hide_box();
		});
	});
	
	$('.cancel_claim').click(function () { // 关闭申诉对话框
		hide_box();
	});
}

function show_update_info () {
	var obj = $('#app_info_more');
	var is_display = obj.css('display');
	//console.log(is_display);
	if (is_display == 'block') {
		obj.hide();
	} else {
		obj.show();
	}
}

function check_market_user_enable (m_id) {
	var r = true;
	$('.markets').each(function () {
		var this_obj = $(this);
		var market_id = this_obj.val();
		var market_name = this_obj.parent().parent().find('.item_name a').html();
		var m_obj = $('#market_username_' + market_id);
		var market_username = m_obj.val();
		var fail_times = m_obj.find('option[value="' + market_username + '"]').attr('_fail_times');
//		console.log(market_id);
		if (!this_obj.attr('checked')) {
			m_obj.css('border-color', $('select').css('border-color'));
			return;
		}
		if (fail_times > 3 && m_obj.css('border-color') != $('select').css('border-color')) {
			return;
		}
		m_obj.css('border-color', $('select').css('border-color'));
		if (m_id && market_id != m_id) {
			return;
		}
		if (fail_times > 3) {
			m_obj.css('border-color', '#f00');
			alert(market_name + ' 的账户（' + market_username + '）不可用。\n请更换账户，或更新绑定密码。\n更多问题请联系管理员或客服！');
			m_obj.focus();
			r = false;
			return false;
		}
	});
	return r;
}

function check_claim () {
	if ($.inArray($(".claim_info_box select[name='user_type']").val(), new Array("公司", "个人")) == -1) {
		alert("“公司/个人”错误！");
		return false;
	}
	if ($(".claim_info_box input[name='email']").val().trim() == "") {
		alert("“邮箱”必须填写，否则我们无法联系到您！");
		return false;
	}
	if ($(".claim_info_box input[name='name']").val().trim() == "") {
		alert("“应用名称”必须填写，否则我们不知道您要申诉哪个应用！");
		return false;
	}
	if ($(".claim_info_box input[name='claim_package_name']").val().trim() == "") {
		alert("“应用包名”必须填写，这是我们区别应用唯一性的标识！");
		return false;
	}
	// 公司用户未填下载官方下载地址
	if ($(".claim_info_box select[name='user_type']").val() == "公司" && $("input[name='download_url']").val().trim() == "") {
		alert("“下载地址”公司类型用户必须填写，这个有助于我们鉴别真伪！");
		return false;
	}
	var mc = 0; // 已填应用在市场上的信息数量
	var mrtn = true; // 检查应用在市场中信息填写情况，false表示成功
	$("tr.cib-item").each(function () {
		var mk = $(this).find("select[name='market_name[]']").val().trim();
		var mu = $(this).find("input[name='market_username[]']").val().trim();
		var mdl = $(this).find("input[name='market_dl_url[]']").val().trim();
		if (mk && mu && mdl) {
			mc++;
		} else if (mk && !mu) {
			mrtn = false;
			alert(mk + "的已在抓猫绑定且发布该的该市场帐号没有填写！");
			return false;
		} else if (mk && !mdl) {
			mrtn = false;
			alert(mk + "的" + mu + "下该应用的下载地址没有填写！");
			return false;
		} else if ((mu || mdl) && !mk) {
			mrtn = false;
			alert("有一项没有选择市场");
			return false;
		}
	});
	if (!mrtn) {
		return false;
	}
	if (mc == 0) {
		alert("至少填写一个应用在市场上的信息，以便我们确认您的应用的所属权！");
		return false;
	}
	return true;
}

/**
 * 上传文件
 *  <div id="upload" class="upload_file"
 *  	upload_url="/app.php?act=upload_file"
 *  	file_size_limit="50 MB"
 *  	file_types="*.jpg;*.gif"
 *  	file_types_description="图片文件"
 *  	button_image_url="/img/button.png"
 *  	button_width="200"
 *  	button_height="30">
 *  	<div class="upload_button"></div><!-- 上传进度 -->
 *  	<div class="file_name">请选择文件...</div><!-- 显示上传文件的名称 -->
 *  	<div class="progress"></div><!-- 上传进度 -->
 *  </div>
 *  
 *  js: upload_file("#upload", function (file, server_data) {});
 */
function upload_file (obj_name, upload_success_handler) {
	var obj = $(obj_name);
	var upload_url = obj.attr("upload_url");
	var file_size_limit = obj.attr("file_size_limit");
	var file_types = obj.attr("file_types");
	var file_types_description = obj.attr("file_types_description");
	var button_image_url = obj.attr("button_image_url");
	var button_width = obj.attr("button_width");
	var button_height = obj.attr("button_height");
	var button_placeholder_id = "spanSWFUploadButton_" + Math.ceil(Math.random() * 1000000000);
	
	// button_placeholder_id
	obj.find(".upload_button").html("<div id=\"" + button_placeholder_id + "\"></div>");
	obj.find(".progress").html("<div>&nbsp;</div>");
	
	// 当选择文件对话框关闭，并且所有选择文件已经处理完成（加入上传队列成功或者失败）时
	function file_dialog_complete_handler_file (selected, queued) {
		if (selected != 1 || queued != 1) {
			return false;
		}
		this.startUpload();
	}
	
	// 当选择文件对话框关闭消失时，如果选择的文件加入到上传队列中失败
	function file_queue_error_handler_file (file, code, message) {
		if (code == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
			alert('选择的文件超过上传最大大小限制（' + file_size_limit + '）');
		} else if (code == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE) {
			alert("请选择正确的文件格式！\n必须是" + file_types_description + "（" + file_types + "）");
		} else {
			alert("选择文件错误！\ncode: " + code);
		}
	}
	
	// 当文件选择对话框关闭消失时
	function file_queued_handler_file (file) {
		obj.find('.file_name').html(file.name);
		obj.find('.file_name').attr("title", file.name);
	}

	// 在文件往服务端上传之前
	function upload_start_handler_file (file) {
		set_uploading_count(1); // 上传计算器加一
	}

	// 上传进度
	function upload_progress_handler_file (file, complete, total) {
		obj.find('.progress div').css('width', Math.ceil((complete / total) * 100) + '%');
	}

	// 当上传队列中的一个文件完成了一个上传周期，不论成功或失败
	function upload_complete_handler_file (file) {
		set_uploading_count(-1); // 上传计数器减一
	}

	// 无论什么时候，只要上传被终止或者没有成功
	function upload_error_handler_file (file, code, message) {
		alert("上传失败，请稍后再试！\ncode: " + code + "\nmessage: " + message);
		obj.find('.file_name').html('上传失败');
		obj.find('.progress div').css('width', '0%');
	}
	
	var settings = {
//		debug: true,
		flash_url: "js/swfupload.swf",
		upload_url: upload_url,
		file_size_limit: file_size_limit,
		file_types: file_types,
		file_types_description: file_types_description,
		
		post_params: {
			'login_user_token': get_cookie('login_user_token')
		},
		
		button_image_url: button_image_url,
		button_width: button_width,
		button_height: button_height,
		button_placeholder_id: button_placeholder_id,
		button_text: '',
		button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE,
		button_cursor: SWFUpload.CURSOR.HAND,
		button_window_mode: SWFUpload.WINDOW_MODE.OPAQUE,
		
		file_dialog_complete_handler: file_dialog_complete_handler_file,
		file_queue_error_handler: file_queue_error_handler_file,
		file_queued_handler: file_queued_handler_file,
		upload_start_handler: upload_start_handler_file,
		upload_progress_handler: upload_progress_handler_file,
		upload_complete_handler: upload_complete_handler_file,
		upload_error_handler: upload_error_handler_file,
		upload_success_handler: upload_success_handler
	};
	
	new SWFUpload(settings);
}

function refresh_verify_img () {
	$('#verify_img').attr('src', _URL_PATH + 'scode.php?r=' + encodeURIComponent(new Date()));
}

function load_verify_img () {
	if (!$('#verify_img').attr('src')) {
		refresh_verify_img();
	}
	$('#verify_code').focus();
}

//网页加载完成后执行
$(function () {
	// 第一步： <div class="tips" body="#tips-text">tips</div>
	// 第二步： <div id="tips-text" class="tips-body">tips内容</div>
	if ($('.tips').length > 0) {
		
		$('.tips').tooltip({
			bodyHandler: function () {
				if ($(this).attr('body') && $($(this).attr('body')).length > 0) {
					return $($(this).attr('body')).html();
				} else {
					return '&nbsp;';
				}
			}
		});
		(new Image()).src = '../img/tips-icon-hover.png';
	}
});

/* HTML加载完成后执行的动作 */
$(function () {
	
	/* app.details */
	$('.tip').hover(function () {
		$(this).find('.tip_box').show();
	}, function () {
		$(this).find('.tip_box').hide();
	});
	
	if ($('#upload_apk').length > 0) {
		upload_apk(act);
	}
	if ($('#icon_up').length > 0) {
		icon_up();
	}
	for (var i = 1; i <= 5; i++) {
		if ($('#screen_box_' + i).length > 0) {
			screen_up(i);
		}
	}
	
	// fix footer position
	if (
			(
					(mod == 'reg' && (act == 's1' || act == 's2' || act == 's3')) ||
					(mod == 'login' && (act == 'in')) ||
					(mod == 'app' && (act == 'list' || act == 'add' || act == 'update')) ||
					(mod == 'user' && (act == 'info' || act == 'pass' || act == 'market_user'))
			) && $(window).height() - $('body').height() > 0
	) {
		fix_height();
	}
	
	$('#app_submit').click(function () {
		
		// 检查绑定的市场账户是否可用
		if (!check_market_user_enable()) {
			return false;
		}
		
		if ( ! app_check_post (act) ) {
			return false;
		}
		
		if (act == 'add' || act == 'reissue') {
			confirm_common_market_user(act);
		} else {
			app_submit();
		}
		
	});
	//重新检查
	
	if ((mod == 'app' && act != 'reissue') || (mod == 'tool' && act == 'import_app_import')) {
		update_info();
	}

	// user.info
	$('#text_user_info_birthday').datepicker({
		dateFormat: 'yy-mm-dd',
		changeMonth: true,
		changeYear: true,
		yearRange: '1900:2012'
	});
	
	if (mod == 'report' && act == 'index') {
		if ($('#report_chart').length > 0) {
			change_chart (0);
		}
	}
	
	/* auto focus */
	// login.in
	if (mod == 'login' && act == 'in') {
		$('#user').focus();
	}
	// reg.s3
	if (mod == 'reg' && act == 's3') {
		$('#user').focus();
	}

	/* IE6 CSS debug, remove later */
	if ($('.css').length > 0) {
		var out = '';
		out += 'display: ' + $('.css').css('display') + "\n";
		out += 'padding: ' + $('.css').css('padding') + "\n";
		out += 'width: ' + $('.css').css('width') + "\n";
		out += 'height: ' + $('.css').css('height') + "\n";
		out += 'margin: ' + $('.css').css('margin') + "\n";
		out += 'position: ' + $('.css').css('position') + "\n";
		out += 'top: ' + $('.css').css('top') + "\n";
		out += 'right: ' + $('.css').css('right') + "\n";
		out += 'bottom: ' + $('.css').css('bottom') + "\n";
		out += 'left: ' + $('.css').css('left') + "\n";
		setTimeout(function () {
			alert(out);
		}, 2000);
	}
	
	/* mod:index 首页 */
	if (mod == 'index') {
		if (act == 'index') {
			// 动画
			$('#slides').slides({
				preload: true,
				preloadImage: _URL_PATH + '/img/loading.gif',
				generatePagination: false,
				play: 5000,
				pause: 2500,
				hoverPause: true,
				generateNextPrev: false,
				animationComplete: function (current) {
					$('#slides .link').each(function () {
						$(this).parent().removeClass('current');
					});
					$('#slides .link:eq(' + (current - 1) + ')').parent().addClass('current');
				}
			});
			
			// tabs
			$("#tabs").tabs();
		}
	}
	
	/* mod:reg 注册 */
	if (mod == 'reg') {
		/* act:s1 填写邮件 */
		if (act == 's1') {
			$('#text_reg_s1_email').focus(); // 页面加载完后聚焦到邮箱的文本框
			// 表单检查
			$('#submit_reg_s1').click(function () {
				// 检查邮件
				if (!$('#text_reg_s1_email').val().isEmail()) {
					alert('邮件未填写或邮件格式错误，请重新填写');
					$('#text_reg_s1_email').focus();
					$('#text_reg_s1_email').addClass('error');
					return false;
				} else {
					$('#text_reg_s1_email').removeClass('error');
				}
				// 检查验证码
				if ($('#verify').val().trim() == '') {
					alert('验证码不能为空，请重新填写');
					$('#verify').focus();
					$('#verify').addClass('error');
					return false;
				} else {
					$('#verify').removeClass('error');
				}
				// 用户许可协议
				if (!$('#checkbox_reg_s1_license').attr('checked')) {
					alert('接受《开发者注册服务条款》才能注册');
					$('#checkbox_reg_s1_license').focus();
					$('#checkbox_reg_s1_license').addClass('error');
					return false;
				} else {
					$('#checkbox_reg_s1_license').removeClass('error');
				}
				// 提交表单
				$('#form_reg_s1').submit();
			});
		}
	}
	/* mod:login 登录/退出 */
	if (mod == 'login') {
		/* act:in 登录 */
		if (act == 'in') {
			$('#text_login_in_username').focus(); // 页面加载完后聚焦到用户名的文本框
			// 表单检查
			$('#submit_login_in').click(function () {
				// 检查用户名
				if (!$('#text_login_in_username').val().isEmail() && !$('#text_login_in_username').val().isUsername()) {
					alert('用户名格式错误，只能是邮箱或4-12位的字母或数字，请重新填写');
					$('#text_login_in_username').focus();
					$('#text_login_in_username').addClass('error');
					return false;
				} else {
					$('#text_login_in_username').removeClass('error');
				}
				// 检查密码
				if (!$('#text_login_in_password').val().isPassword()) {
					alert('密码长度必须是6-20位，请重新填写');
					$('#text_login_in_password').focus();
					$('#text_login_in_password').addClass('error');
					return false;
				} else {
					$('#text_login_in_password').removeClass('error');
				}
				// 提交表单
				$('#form_login_in').submit();
			});
		}
		/* act:findpass 找回密码 */
		if (act == 'findpass') {
			// 表单检查
			$('#submit_login_findpass').click(function () {
				// 检查邮件
				if (!$('#text_login_findpass_email').val().isEmail()) {
					alert('邮件未填写或邮件格式错误，请重新填写');
					$('#text_login_findpass_email').focus();
					$('#text_login_findpass_email').addClass('error');
					return false;
				} else {
					$('#text_login_findpass_email').removeClass('error');
				}
				// 检查验证码
				if ($('#verify').val().trim() == '') {
					alert('验证码不能为空，请重新填写');
					$('#verify').focus();
					$('#verify').addClass('error');
					return false;
				} else {
					$('#verify').removeClass('error');
				}
				// 提交表单
				$('#form_login_findpass').submit();
			});
		}
	}
	
	/* mod:user */
	if (mod == 'user') {
		/* act:info 用户基本信息 */
		if (act == 'info') {
			// 表单检查
			$('#submit_user_info').click(function () {
				/* 必填字段 */
				// 开发者
				if ($('#text_user_info_full_name').val().trim().relLength() < 4 || $('#text_user_info_full_name').val().trim().relLength() > 20) {
					alert('开发者名称必须是4-20位的字符，汉字算两个字符');
					$('#text_user_info_full_name').focus();
					$('#text_user_info_full_name').addClass('error');
					return false;
				} else {
					$('#text_user_info_full_name').removeClass('error');
				}
				// 客服电话
				if (!$('#text_user_info_phone').val().trim().isPhone() && !$('#text_user_info_phone').val().trim().isMobile()) {
					alert('客服的格式必须为：\n区号-电话(-分机)\n也可是是手机号 或 400 / 800 电话\n请检查后重新填写！');
					$('#text_user_info_phone').focus();
					$('#text_user_info_phone').addClass('error');
					return false;
				} else {
					$('#text_user_info_phone').removeClass('error');
				}
				// 官方网址
				if (!$('#text_user_info_website').val().trim().isUrl()) {
					alert('官方网址未填写或格式错误，请检查后重新填写！');
					$('#text_user_info_website').focus();
					$('#text_user_info_website').addClass('error');
					return false;
				} else {
					$('#text_user_info_website').removeClass('error');
				}
				// 客服邮箱
				if (!$('#text_user_info_support_email').val().trim().isEmail()) {
					alert('客服邮箱未填写或格式错误，请检查后重新填写！');
					$('#text_user_info_support_email').focus();
					$('#text_user_info_support_email').addClass('error');
					return false;
				} else {
					$('#text_user_info_support_email').removeClass('error');
				}
				// 手机
				if (!$('#text_user_info_mobile').val().trim().isMobile()) {
					alert('手机号码未填写或格式错误，请检查后重新填写！');
					$('#text_user_info_mobile').focus();
					$('#text_user_info_mobile').addClass('error');
					return false;
				} else {
					$('#text_user_info_mobile').removeClass('error');
				}
				// GTalk、QQ、MSN必须填一个
				if (!$('#text_user_info_gtalk').val().trim() && !$('#text_user_info_qq').val().trim() && !$('#text_user_info_msn').val().trim()) {
					alert('GTalk、QQ、MSN必须填一个。');
					$('#text_user_info_gtalk').focus();
					$('#text_user_info_gtalk').addClass('error');
					$('#text_user_info_qq').addClass('error');
					$('#text_user_info_msn').addClass('error');
					return false;
				} else {
					$('#text_user_info_gtalk').removeClass('error');
					$('#text_user_info_qq').removeClass('error');
					$('#text_user_info_msn').removeClass('error');
				}
				/* 非必填字段 */
//				// 地址
//				if (!($('#text_user_info_address').val() && $('#text_user_info_p').val() > 0 && $('#text_user_info_c').val() > 0)) {
//					alert('地址的格式不对，请检查后重新填写！');
//					$('#text_user_info_address').focus();
//					$('#text_user_info_address').addClass('error');
//					return false;
//				} else {
//					$('#text_user_info_address').removeClass('error');
//				}
				// 生日
				if ($('#text_user_info_birthday').val().trim() && !$('#text_user_info_birthday').val().trim().match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
					alert('生日格式必须为：\nyyyy-mm-dd\n请检查后重新填写！');
					$('#text_user_info_birthday').focus();
					$('#text_user_info_birthday').addClass('error');
					return false;
				} else {
					$('#text_user_info_birthday').removeClass('error');
				}
				// Gtalk
				if ($('#text_user_info_gtalk').val().trim() && !$('#text_user_info_gtalk').val().trim().isEmail()) {
					alert('Gtalk格式错误，请检查后重新填写！');
					$('#text_user_info_gtalk').focus();
					$('#text_user_info_gtalk').addClass('error');
					return false;
				} else {
					$('#text_user_info_gtalk').removeClass('error');
				}
				// MSN
				if ($('#text_user_info_msn').val().trim() && !$('#text_user_info_msn').val().trim().isEmail()) {
					alert('MSN格式错误，请检查后重新填写！');
					$('#text_user_info_msn').focus();
					$('#text_user_info_msn').addClass('error');
					return false;
				} else {
					$('#text_user_info_msn').removeClass('error');
				}
				// QQ
				if ($('#text_user_info_qq').val().trim() && !$('#text_user_info_qq').val().trim().match(/^[0-9]{6,11}$/) && !$('#text_user_info_qq').val().trim().isEmail()) {
					alert('QQ格式错误，请检查后重新填写！');
					$('#text_user_info_qq').focus();
					$('#text_user_info_qq').addClass('error');
					return false;
				} else {
					$('#text_user_info_qq').removeClass('error');
				}
				// 微博
				if ($('#text_user_info_weibo').val().trim() && !$('#text_user_info_weibo').val().trim().isUrl()) {
					alert('微博格式错误，请检查后重新填写！');
					$('#text_user_info_weibo').focus();
					$('#text_user_info_weibo').addClass('error');
					return false;
				} else {
					$('#text_user_info_weibo').removeClass('error');
				}
				// 提交表单
				$('#form_user_info').submit();
			});
		}
		
		// 消息
		if (act == 'message') {
			
			var market_id = $('#market_id').val();
			var page = $('.pagination').attr('_page');
			
			$('.message ul li').each(function () {
				var obj = $(this);
				var id = obj.attr('_id');
				
				if (obj.hasClass('noread')) { // 未读的消息
					var timeout;
					obj.hover(function () { // 鼠标放上去
						timeout = setTimeout(function () { // 时间超过2秒
							$.ajax({ // 标记为已阅读
								dataType: 'json',
								url: _URL_PATH + '/user.php?act=message&op=set_read&id=' + id,
								success: function (data) {
									if (data == '1') {
										obj.removeClass('noread');
									}
								}
							});
						}, 1000);
					}, function () {
						clearTimeout(timeout);
					});
				}
				
				obj.find('.delete').click(function () {
//					console.log(market_id);
					if (confirm('确定要删除本条消息吗？')) {
						window.location = '/user.php?act=message&op=delete&id=' + id + (market_id ? '&market_id=' + market_id : '') + (page > 1 ? '&page=' + page : '');
					}
				});
			});
		}
	}
	
	/* mod:app */
	if (mod == 'app') {
		/* act:update */
		update_comfirm_box(market_can_not_update_json);
		
		/* act:add 添加 */
		if (act == 'add') {
			// 下载合作伙伴的 apk 文件
			if ($('#apk_url').length > 0) {
				download_partner_apk();
			}
		}
		
		/* act:info 添加，更新，补发 */
		if (act == 'add' || act == 'update' || act == 'reissue') {
			// 不检查 apk 的市场
			for (var i = 0, n = _NOT_CHECK_APK_MARKET_IDS.length; i < n; i++) {
				change_market_li_status(_NOT_CHECK_APK_MARKET_IDS[i], 1, '', '', true);
				$('#app_recheck_' + _NOT_CHECK_APK_MARKET_IDS[i]).hide();
				$('#app_ignore_' + _NOT_CHECK_APK_MARKET_IDS[i]).hide();
			}
			
			// 不能使用公共帐号 且 未绑定公共帐号
			for (var i = 0, n = _NOT_USE_PUBLIC_ACCOUNT_MARKET_IDS.length; i < n; i++) {
				if ($.inArray(_NOT_USE_PUBLIC_ACCOUNT_MARKET_IDS[i], _NOT_BINDING_USER_ACCOUNT_MARKET_IDS) > -1) {
					change_market_li_status(_NOT_USE_PUBLIC_ACCOUNT_MARKET_IDS[i], 1, '', '#FFFFAA', false, true);
				}
			}
			
			// 不可更新的市场
			for (var i = 0, n = market_can_not_update_json.length; i < n; i++) {
				change_market_li_status(market_can_not_update_json[i].id, -1, market_can_not_update_json[i].status + '，暂时无法更新', '#EEE', false, true);
				$('#app_recheck_' + market_can_not_update_json[i].id).hide();
				$('#app_ignore_' + market_can_not_update_json[i].id).hide();
			}
			
			// 被关闭的市场背景显示灰色，且不可用
			for (var i = 0, n = _CLOSED_MARKET_IDS.length; i < n; i++) {
				change_market_li_status(_CLOSED_MARKET_IDS[i], -1, _CLOSED_MARKET_REASONS[_CLOSED_MARKET_IDS[i]], '#EEE', false, true);
				$('#app_recheck_' + _CLOSED_MARKET_IDS[i]).hide();
				$('#app_ignore_' + _CLOSED_MARKET_IDS[i]).hide();
			}
		}

		/* act:reissue 补发 */
		if (act == 'reissue') {
			// show upload private apk UI
			var package_name = $('#package_name').val();
			var ver_code = $('#ver_code').val();
			for (var i = 0, n = markets_ids.length; i < n; i++) {
				priv_apk_up (markets_ids[i], package_name, ver_code);
			}
			
			check_apk($('#package_name').val());
		}

		//针对wo nearme，sohu等检查重复的appname 并提示给用户
		$('#label').blur(function(){
			check_appname();
		});
	}
	
	/* mod:tool */
	if (mod == 'tool') {
		if (act == 'import_app_import') {
			$('#app_s2').show();
		}
	}
	
	// EOE市场需要上传授权文件
	if ($('.eoe-cy').length > 0) {
		if ($("input[name='market[3]']").attr("checked")) {
			$('.eoe-cy').slideDown();
		}
		$("input[name='market[3]']").click(function () {
			if ($('#market_username_3').attr('has_user_account') > 0) {
				if ($(this).attr("checked")) {
					$('.eoe-cy').slideDown();
				} else {
					$('.eoe-cy').slideUp();
				}
			}
		});
	}
	if ($("#cy_img_3").length > 0) {
		upload_file("#cy_img_3", function (file, data) {
//			console.log(data);
			var data = eval("(" + data + ")");
			if (data.status == 0) {
				$("#cy_img_3").find(".file_name").html(data.data.file);
				$("#cy_img_3").find(".file_name").attr("title", data.data.file);
				$("#copyright_image_3").val(data.data.file);
			} else {
				alert("上传失败！\n" + data.message);
			}
		});
	}
	if ($("#cy_file_3").length > 0) {
		upload_file("#cy_file_3", function (file, data) {
			var data = eval("(" + data + ")");
			if (data.status == 0) {
				$("#cy_file_3").find(".file_name").html(data.data.file);
				$("#cy_file_3").find(".file_name").attr("title", data.data.file);
				$("#copyright_file_3").val(data.data.file);
			} else {
				alert("上传失败！\n" + data.message);
			}
		});
	}
});



//图片旋转
$(function () {
	$('#image_turn_ul a').click(function(){
		var screen_image_id = $(this).attr('screen_image_id');
		var is_right = 1;
		if($(this).hasClass('left')){
			is_right = 0;
		}
		var screen_url = $('#screen_url_'+screen_image_id).val();
		if(screen_url) {
			$.ajax({
				dataType: 'json',
				url: _URL_PATH + '/app.php?act=screen_turn&screen_image_id='+screen_image_id+'&screen_url='+screen_url+'&is_right=' + is_right,
				success: function (data) {
					//alert(data);
					if (data.success && data.screen_file && data.screen_url) {
						var data_screen_image_id = data.screen_image_id;
						var data_screen_file = data.screen_file;
						var data_screen_url = data.screen_url;
			
						$('#screen_url_'+data_screen_image_id).val(data_screen_file);
						$('#screen_img_'+data_screen_image_id).attr('src',data_screen_url);
					}
				}
			});
			
		}
		
	});	
});

/* market_extension页面JS   */
function show_user_count_detail(){
	if($('select[name=user_count] option:selected').val() == '其他'){
		$('.user_count_detail').show();	
	}
	else{
		$("input[name=user_count_detail]").val("")
		$('.user_count_detail').hide();
	}
}

function show_formual(){
	if($('input:radio[name=reverse_quotes]:checked').val() == '是'){
		$('#tr_formula').show();
	}
	else{
		$('#tr_formula').hide();
	}	
}

$('#market_extension_textarea').click(function(){
	if($('#market_extension_textarea').val() == "提示：如有其他附加信息（如联系方式等），请在此处填写。"){
		$('#market_extension_textarea').val('');
		$('#market_extension_textarea').css('color','#000');
	}
	$('#market_extension_textarea').blur(function(){
		if($('#market_extension_textarea').val() == ''){
			$('#market_extension_textarea').css('color','#ccc');
			$('#market_extension_textarea').val("提示：如有其他附加信息（如联系方式等），请在此处填写。");
		}
	})
})


var formula_value = $('#formula').val(); /*全局变量，记录$('#formula')初始值*/
$('#formula').click(function(){
	if($('#formula').val() == formula_value){
		$('#formula').val('');
		$('#formula').css('color','#000');
	}
	$('#formula').blur(function(){
		if($('#formula').val() == ''){
			$('#formula').css('color','#ccc');
			$('#formula').val(formula_value);
		}
	})
})

function submit_market_extension(url,act){
	var budget = $("input[name=budget]").val();
	var reg = /^\d+$/ ;
	if(budget == ""){
		alert("预算未填写")
		$("input[name=budget]").focus();
		return false;
	}
	else if(!reg.test(budget)){
		alert("预算必须为正整数")
		$("input[name=budget]").focus();
		return false;	
	}
	var user_count = $(".user_count").val();
	var user_count_detail = $("input[name=user_count_detail]").val();
	if(user_count == "其他" && user_count_detail == "" ){
		alert("应用用户量未填写")
		return false;
	}
	if( user_count_detail != "" && !reg.test(user_count_detail)){
		alert("应用用户量必须为正整数");
		$("input[name=user_count_detail]").focus();
		return false;
	}
	var wheather_advertise = $(".wheather_advertise").val();
	if(wheather_advertise == "-- 请选择 --" || wheather_advertise == "" ){
		alert("是否有广告未选择")
		$(".wheather_advertise").focus();
		return false;
	}

	var type = $("input[name=type]").val();
	if(type == ""){
		alert("类别未填写")
		$("input[name=type]").focus();
		return false;
	}
	var formula = $("#formula").val();
	if(formula == formula_value){
		formula = "";
	}else{
		formula=formula.replace(/\n/g,"<br>");
	}
	var addtional_information = $("#market_extension_textarea").val();
	if(addtional_information == "提示：如有其他附加信息（如联系方式等），请在此处填写。"){
		addtional_information = "";
	}else{
		addtional_information = addtional_information.replace(/\n/g,"<br>");
	}
	var user_id = $("input[name=user_id]").val();
	var package_id = $("input[name=package_id]").val();
	var app_name = $("input[name=app_name]").val();
	var ver_name = $("input[name=ver_name]").val();
	var extension_model = $("input[name=extension_model]:checked").val();
	var backstage = $("input[name=backstage]").val();
	var reverse_quotes = $("input[name=reverse_quotes]:checked").val();
	var billing_cycles = $("input[name=billing_cycles]:checked").val();
	var wheather_charges = $("input[name=wheather_charges]:checked").val();
	$.ajax({
		type:'get',
		url:url,
		data:'user_id='+encodeURIComponent(user_id)+'&package_id='+encodeURIComponent(package_id)+'&app_name='+encodeURIComponent(app_name)+'&ver_name='+encodeURIComponent(ver_name)+'&type='+encodeURIComponent(type)+'&formula='+encodeURIComponent(formula)+'&extension_model='+encodeURIComponent(extension_model)+'&budget='+encodeURIComponent(budget)+'&backstage='+encodeURIComponent(backstage)+'&reverse_quotes='+encodeURIComponent(reverse_quotes)+'&billing_cycles='+encodeURIComponent(billing_cycles)+'&user_count='+encodeURIComponent(user_count)+'&user_count_detail='+encodeURIComponent(user_count_detail)+'&wheather_charges='+encodeURIComponent(wheather_charges)+'&wheather_advertise='+encodeURIComponent(wheather_advertise)+'&addtional_information='+encodeURIComponent(addtional_information)+'&act='+encodeURIComponent(act),
		dataType:'json',
		success:function(data){
			if(data.success){
				alert(data.success);
			}
			else if(data.error){
				alert(data.error);
				return false;
			}
		window.location.href = "/app.php?act=details&package_id="+package_id;
		}	
	})
}

function enable_formula(){
	var extension_model = $("input[name=extension_model]:checked").val();
	var billing_cycles = $("input[name=billing_cycles]:checked").val();
	if(extension_model == 'CPA' && billing_cycles == '后付费'){
		$('#reverse_quotes').show();
	}else{
		$('#reverse_quotes').hide();
		$("input[name=reverse_quotes]:last").attr("checked","checked");
		$('#tr_formula').hide();
	}
	
}

/* market_extension页面JS */

$(function () {
	$('.import_app_link').click(function () {
		var market_id = $(this).attr('_market_id');
		var market_username = $('.market_' + market_id + '_user').val();
		if (!market_username) {
			alert('请选择要接管的市场账户。');
			return false;
		}
		show_loading(true, '正在获取市场上的应用列表，请稍后……');
		location.href = '/tool.php?act=import_app_guide&market_id=' + market_id + '&market_username=' + market_username;
	});
});

/**
 * 安智市场，选择电子图书分类时必须要上传授权证明文件
 */
$(function () {
	if ($('#market_cate_7').val() == '1,53' || $('#market_cate_7').val() == '1,55') {
		$('.anzhi_cy').slideDown();
	}
	$('#market_cate_7').change(function () {
		if ($(this).val() != '1,53' && $(this).val() != '1,55') $('.anzhi_cy').slideUp();
		else $('.anzhi_cy').slideDown();
	});
	if ($('#cy_cbl_up_7').length > 0) {
		upload_file("#cy_cbl_up_7", function (file, data) {
			var data = eval("(" + data + ")");
			if (data.status == 0) {
				$("#cy_cbl_up_7").find(".file_name").html(data.data.file);
				$("#cy_cbl_up_7").find(".file_name").attr("title", data.data.file);
				$("#cy_cbl_7").val(data.data.file);
			} else {
				alert("上传失败！\n" + data.message);
			}
		});
	}
	if ($('#cy_lric_up_7').length > 0) {
		upload_file("#cy_lric_up_7", function (file, data) {
			var data = eval("(" + data + ")");
			if (data.status == 0) {
				$("#cy_lric_up_7").find(".file_name").html(data.data.file);
				$("#cy_lric_up_7").find(".file_name").attr("title", data.data.file);
				$("#cy_lric_7").val(data.data.file);
			} else {
				alert("上传失败！\n" + data.message);
			}
		});
	}
	if ($('#cy_cyp_up_7').length > 0) {
		upload_file("#cy_cyp_up_7", function (file, data) {
			var data = eval("(" + data + ")");
			if (data.status == 0) {
				$("#cy_cyp_up_7").find(".file_name").html(data.data.file);
				$("#cy_cyp_up_7").find(".file_name").attr("title", data.data.file);
				$("#cy_cyp_7").val(data.data.file);
			} else {
				alert("上传失败！\n" + data.message);
			}
		});
	}
});
